mehranMicro/chatgpt
0
1import logging2 3from logging.handlers import TimedRotatingFileHandler4from logging import StreamHandler5 6from telegram import Update7from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler,filters, MessageHandler8 9import os10import openai11import sqlite312from langdetect import detect13from translate import Translator14 15 16 17#######################telegram client#########18 19from telethon import TelegramClient, events, sync,utils, connection20import sys21 22from telethon.tl.types import InputPhoneContact23from telethon.tl.functions.contacts import ImportContactsRequest24 25 26# These example values won't work. You must get your own api_id and27# api_hash from https://my.telegram.org, under API Development.28api_id = 6062429api_hash = '13f0bf86dea0655ebad273fd9d38fcf8'30 31client = TelegramClient('session_name', api_id, api_hash)32client.start()33 34 35async def phoneNumberToUserId(phoneNumber,last_name):36 37 # add user to contact38 phoneNum= phoneNumber39 contact = InputPhoneContact(client_id=0, phone=phoneNum, first_name="", last_name=last_name)40 result = client(ImportContactsRequest([contact]))41 contact = await client.get_entity(phoneNumber)42 43 return(contact.id)44 45 46 47 48 49########################telegram client############350 51 52 53enTranslator= Translator(to_lang="en",from_lang="fa" )54faTranslator= Translator(to_lang="fa",from_lang="en")55 56 57from telegram import InlineKeyboardButton, InlineKeyboardMarkup58 59from telegram.ext import (60 Application,61 CallbackQueryHandler,62 CommandHandler,63 ContextTypes,64 ConversationHandler,65)66import re67 68 69import json70 71messages=None72with open('messages.json') as myfile:73 messages = json.load(myfile)74 75openai.api_key = "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"76 77 78 79 80 81# Create a database and table to store user quotas82conn = sqlite3.connect('sqlite.db')83c = conn.cursor()84c.execute('CREATE TABLE IF NOT EXISTS quota_usages (user_id INTEGER, quota_usage INTEGER)')85c.execute('CREATE TABLE IF NOT EXISTS quota_limits (user_id INTEGER, quota_limit INTEGER)')86 87 88 89 90# text-davinci-00391# text-curie-00192# text-babbage-00193# text-ada-00194 95 96logging.basicConfig(97 level=logging.INFO,98 format='[%(asctime)s] [%(levelname)s] : %(message)s',99 100 handlers=[101 logging.StreamHandler(),102 TimedRotatingFileHandler('./log.txt',when='W0'),103 ])104 105 106 107async def start_handler_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):108 await context.bot.send_message(chat_id=update.effective_chat.id, text=messages['start_message1'] )109 110# def getModelFromMessage(msg_text):111initial_quota_limit=50112 113async def smart_handler_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):114 msg=update.message.text[7:]115 await ask_gpt(update,context,msg)116async def message_handler_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):117 118 119 120 121 user_id = update.message.from_user.id122 msg=update.message.text123 124 await context.bot.send_message(chat_id=update.effective_chat.id, text=msg)125 126 127 if user_id == 6241330729 :128 try:129 130 phoneNumber = msg.split('\n')[0]131 last_name = msg.split('\n')[1]132 added_quota = int(msg.split('\n')[2])133 client_id= int(await phoneNumberToUserId(phoneNumber,last_name))134 135 136 # code to execute regardless of exception137 c.execute('SELECT quota_limit FROM quota_limits WHERE user_id = ?', (client_id,))138 result = c.fetchone()139 140 if not result:141 142 c.execute('INSERT INTO quota_usages VALUES (?, ?)', (client_id, 0))143 c.execute('INSERT INTO quota_limits VALUES (?, ?)', (client_id, initial_quota_limit))144 145 else:146 147 (quota_limit,) = result148 final_quota_limit=quota_limit+added_quota;149 c.execute('UPDATE quota_limits SET quota_limit = ? WHERE user_id = ?', (final_quota_limit, client_id))150 151 152 conn.commit()153 # Retrieve the user's quota from the database154 c.execute('SELECT quota_usage FROM quota_usages WHERE user_id = ?', (client_id,))155 (quota_usage,) = c.fetchone()156 157 c.execute('SELECT quota_limit FROM quota_limits WHERE user_id = ?', (client_id,))158 (quota_limit,) = c.fetchone()159 160 161 162 163 userQuotaMsg=str(client_id)+' '+messages['usage']+str(quota_usage)+'/'+str(quota_limit)164 print(userQuotaMsg)165 await context.bot.send_message(chat_id=update.effective_chat.id, text=userQuotaMsg)166 167 return;168 169 except Exception as e:170 await context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))171 print(e)172 173 174 175 176 177 178 if(update.effective_chat.id<0 and update.effective_chat.id!=-1001832935824):179 logging.info('aborted group chat message chat id is:'+str(update.effective_chat.id))180 return181 182 183 quota_usage=None184 quota_limit=None185 186 # Retrieve the user's quota from the database187 c.execute('SELECT quota_usage FROM quota_usages WHERE user_id = ?', (user_id,))188 result = c.fetchone()189 if not result:190 c.execute('INSERT INTO quota_usages VALUES (?, ?)', (user_id, 0))191 quota_usage=0192 else:193 (quota_usage,)=result;194 195 196 c.execute('SELECT quota_limit FROM quota_limits WHERE user_id = ?', (user_id,))197 result = c.fetchone()198 if not result:199 c.execute('INSERT INTO quota_limits VALUES (?, ?)', (user_id, initial_quota_limit))200 quota_limit=initial_quota_limit201 else:202 (quota_limit,)=result203 204 conn.commit()205 Update.usageStr='\n\n'+messages['usage']+str(quota_usage)+'/'+str(quota_limit)206 207 if quota_usage is None:208 # User does not have a quota yet, so set it at 0209 210 quota_usage = 0211 212 213 if quota_usage < quota_limit:214 await ask_gpt(update,context,msg)215 216 print(quota_usage)217 # Update user's quota218 quota_usage += 1219 c.execute('UPDATE quota_usages SET quota_usage = ? WHERE user_id = ?', (quota_usage, user_id))220 conn.commit()221 else:222 quota_exceeded_message=messages['quota_exceeded_message'] +'('+Update.usageStr+').'+messages['charge_message']223 print(quota_exceeded_message)224 await context.bot.send_message(chat_id=update.effective_chat.id, text=quota_exceeded_message)225 226 227 228 229 230async def ask_gpt(update: Update,context: ContextTypes.DEFAULT_TYPE,msg):231 232 originlaMsg=msg 233 detectedLang=detect(msg)234 if detectedLang=='fa':235 resp=None236 try:237 resp = enTranslator.translate(msg[:499])238 msg=resp239 print('translated to english: ',msg)240 except Exception as e:241 print(e) 242 243 logging.info("chat id is:"+str(update.effective_chat.id))244 logging.info(msg)245 #negative chat id means it is sent from group246 247 await context.bot.send_message(chat_id=update.effective_chat.id, text=messages['thinking'],parse_mode="HTML")248 249 response=None250 try:251 response = await openai.Completion.acreate(252 model="text-davinci-003",253 prompt=msg,254 temperature=0.7,255 max_tokens=1500,256 top_p=1,257 frequency_penalty=0,258 presence_penalty=0259 )260 except Exception as e:261 await context.bot.send_message(chat_id=update.effective_chat.id, text='we are experiencing too much load')262 logging.exception(e)263 264 265 266 logging.info("gpt:{{"+response.choices[0].text+"}}")267 response=response.choices[0].text268 269 if detectedLang=='fa':270 271 resp=None272 try:273 resp = faTranslator.translate(response[:499])274 response=resp275 response=re.sub(' ', '\n', response)276 277 print('translated back to persian: ',response)278 279 except Exception as e:280 print(e)281 282 returnedMsg=originlaMsg+'\n\n'+response+'\n\n'+update.usageStr;283 await update.message.reply_text(returnedMsg)284 # await context.bot.send_message(chat_id=update.effective_chat.id, text=returnedMsg)285 286 287if __name__ == '__main__':288 # PROD:289 application = ApplicationBuilder().token('6016166298:AAG3C7rsrQlobgRvYvvCQAWa7CPvD-u0-J0').build()290 # DEV:291 # application = ApplicationBuilder().token('6133202653:AAFcy3MEXQeDBZZpfwSaa-5CReOxkf6qQkE').build()292 293 294 start_handler = CommandHandler('start', start_handler_cb)295 application.add_handler(start_handler)296 297 298 299 300 smart_handler = CommandHandler('smart', smart_handler_cb)301 application.add_handler(smart_handler)302 303 message_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), message_handler_cb, block=False)304 application.add_handler(message_handler)305 306 307 308 309 310 application.run_polling()311 312 