mehranMicro commited on
Commit
3a6cc28
1 Parent(s): 5759cdb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +311 -0
app.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from logging.handlers import TimedRotatingFileHandler
4
+ from logging import StreamHandler
5
+
6
+ from telegram import Update
7
+ from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler,filters, MessageHandler
8
+
9
+ import os
10
+ import openai
11
+ import sqlite3
12
+ from langdetect import detect
13
+ from translate import Translator
14
+
15
+
16
+
17
+ #######################telegram client#########
18
+
19
+ from telethon import TelegramClient, events, sync,utils, connection
20
+ import sys
21
+
22
+ from telethon.tl.types import InputPhoneContact
23
+ from telethon.tl.functions.contacts import ImportContactsRequest
24
+
25
+
26
+ # These example values won't work. You must get your own api_id and
27
+ # api_hash from https://my.telegram.org, under API Development.
28
+ api_id = 60624
29
+ api_hash = '13f0bf86dea0655ebad273fd9d38fcf8'
30
+
31
+ client = TelegramClient('session_name', api_id, api_hash)
32
+ client.start()
33
+
34
+
35
+ async def phoneNumberToUserId(phoneNumber,last_name):
36
+
37
+ # add user to contact
38
+ phoneNum= phoneNumber
39
+ 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############3
50
+
51
+
52
+
53
+ enTranslator= Translator(to_lang="en",from_lang="fa" )
54
+ faTranslator= Translator(to_lang="fa",from_lang="en")
55
+
56
+
57
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
58
+
59
+ from telegram.ext import (
60
+ Application,
61
+ CallbackQueryHandler,
62
+ CommandHandler,
63
+ ContextTypes,
64
+ ConversationHandler,
65
+ )
66
+ import re
67
+
68
+
69
+ import json
70
+
71
+ messages=None
72
+ with open('messages.json') as myfile:
73
+ messages = json.load(myfile)
74
+
75
+ openai.api_key = "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"
76
+
77
+
78
+
79
+
80
+
81
+ # Create a database and table to store user quotas
82
+ conn = sqlite3.connect('sqlite.db')
83
+ c = conn.cursor()
84
+ c.execute('CREATE TABLE IF NOT EXISTS quota_usages (user_id INTEGER, quota_usage INTEGER)')
85
+ c.execute('CREATE TABLE IF NOT EXISTS quota_limits (user_id INTEGER, quota_limit INTEGER)')
86
+
87
+
88
+
89
+
90
+ # text-davinci-003
91
+ # text-curie-001
92
+ # text-babbage-001
93
+ # text-ada-001
94
+
95
+
96
+ logging.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
+
107
+ async 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):
111
+ initial_quota_limit=50
112
+
113
+ async def smart_handler_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):
114
+ msg=update.message.text[7:]
115
+ await ask_gpt(update,context,msg)
116
+ async def message_handler_cb(update: Update, context: ContextTypes.DEFAULT_TYPE):
117
+
118
+
119
+
120
+
121
+ user_id = update.message.from_user.id
122
+ msg=update.message.text
123
+
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 exception
137
+ 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,) = result
148
+ 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 database
154
+ 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
+ return
181
+
182
+
183
+ quota_usage=None
184
+ quota_limit=None
185
+
186
+ # Retrieve the user's quota from the database
187
+ 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=0
192
+ 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_limit
201
+ else:
202
+ (quota_limit,)=result
203
+
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 0
209
+
210
+ quota_usage = 0
211
+
212
+
213
+ if quota_usage < quota_limit:
214
+ await ask_gpt(update,context,msg)
215
+
216
+ print(quota_usage)
217
+ # Update user's quota
218
+ quota_usage += 1
219
+ 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
+
230
+ async def ask_gpt(update: Update,context: ContextTypes.DEFAULT_TYPE,msg):
231
+
232
+ originlaMsg=msg
233
+ detectedLang=detect(msg)
234
+ if detectedLang=='fa':
235
+ resp=None
236
+ try:
237
+ resp = enTranslator.translate(msg[:499])
238
+ msg=resp
239
+ 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 group
246
+
247
+ await context.bot.send_message(chat_id=update.effective_chat.id, text=messages['thinking'],parse_mode="HTML")
248
+
249
+ response=None
250
+ 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=0
259
+ )
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].text
268
+
269
+ if detectedLang=='fa':
270
+
271
+ resp=None
272
+ try:
273
+ resp = faTranslator.translate(response[:499])
274
+ response=resp
275
+ response=re.sub('&#10;', '\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
+
287
+ if __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
+