forked from harshitethic/ChatGPT-Telegram-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
harshitethic.py
324 lines (288 loc) · 9.72 KB
/
harshitethic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from datetime import datetime
import json, os, string, sys, threading, logging, time, re, random
import openai
#OpenAI API key
aienv = os.getenv('OPENAI_KEY')
if aienv == None:
openai.api_key = "ENTER YOUR API KEY HERE"
else:
openai.api_key = aienv
print(aienv)
#Telegram bot key
tgenv = os.getenv('TELEGRAM_KEY')
if tgenv == None:
tgkey = "ENTER YOUR TELEGRAM TOKEN HERE"
else:
tgkey = tgenv
print(tgenv)
# Lots of console output
debug = True
# User Session timeout
timstart = 300
tim = 1
#Defaults
user = ""
running = False
cache = None
qcache = None
chat_log = None
botname = 'Harshit ethic'
username = 'harshitethic_bot'
# Max chat log length (A token is about 4 letters and max tokens is 2048)
max = int(3000)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
completion = openai.Completion()
##################
#Command handlers#
##################
def start(bot, update):
"""Send a message when the command /start is issued."""
global chat_log
global qcache
global cache
global tim
global botname
global username
left = str(tim)
if tim == 1:
chat_log = None
cache = None
qcache = None
botname = 'Harshit Ethic'
username = 'harshitethic_bot'
update.message.reply_text('Hi')
return
else:
update.message.reply_text('I am currently talking to someone else. Can you please wait ' + left + ' seconds?')
return
def help(bot, update):
"""Send a message when the command /help is issued."""
update.message.reply_text('[/reset] resets the conversation,\n [/retry] retries the last output,\n [/username name] sets your name to the bot, default is "Human",\n [/botname name] sets the bots character name, default is "AI"')
def reset(bot, update):
"""Send a message when the command /reset is issued."""
global chat_log
global cache
global qcache
global tim
global botname
global username
left = str(tim)
if user == update.message.from_user.id:
chat_log = None
cache = None
qcache = None
botname = 'Harshit Ethic'
username = 'harshitethic_bot'
update.message.reply_text('Bot has been reset, send a message!')
return
if tim == 1:
chat_log = None
cache = None
qcache = None
botname = 'Harshit Ethic'
username = 'harshitethic_bot'
update.message.reply_text('Bot has been reset, send a message!')
return
else:
update.message.reply_text('I am currently talking to someone else. Can you please wait ' + left + ' seconds?')
return
def retry(bot, update):
"""Send a message when the command /retry is issued."""
global chat_log
global cache
global qcache
global tim
global botname
global username
left = str(tim)
if user == update.message.from_user.id:
new = True
comput = threading.Thread(target=wait, args=(bot, update, botname, username, new,))
comput.start()
return
if tim == 1:
chat_log = None
cache = None
qcache = None
botname = 'Harshit Ethic'
username = 'harshitethic_bot'
update.message.reply_text('Send a message!')
return
else:
update.message.reply_text('I am currently talking to someone else. Can you please wait ' + left + ' seconds?')
return
def runn(bot, update):
"""Send a message when a message is received."""
new = False
global botname
global username
if "/botname " in update.message.text:
try:
string = update.message.text
charout = string.split("/botname ",1)[1]
botname = charout
response = "The bot character name set to: " + botname
update.message.reply_text(response)
except Exception as e:
update.message.reply_text(e)
return
if "/username " in update.message.text:
try:
string = update.message.text
userout = string.split("/username ",1)[1]
username = userout
response = "Your character name set to: " + username
update.message.reply_text(response)
except Exception as e:
update.message.reply_text(e)
return
else:
comput = threading.Thread(target=interact, args=(bot, update, botname, username, new,))
comput.start()
def wait(bot, update, botname, username, new):
global user
global chat_log
global cache
global qcache
global tim
global running
if user == "":
user = update.message.from_user.id
if user == update.message.from_user.id:
tim = timstart
compute = threading.Thread(target=interact, args=(bot, update, botname, username, new,))
compute.start()
if running == False:
while tim > 1:
running = True
time.sleep(1)
tim = tim - 1
if running == True:
chat_log = None
cache = None
qcache = None
user = ""
username = 'harshitethic_bot'
botname = 'Harshit Ethic'
update.message.reply_text('Timer has run down, bot has been reset to defaults.')
running = False
else:
left = str(tim)
update.message.reply_text('I am currently talking to someone else. Can you please wait ' + left + ' seconds?')
################
#Main functions#
################
def limit(text, max):
if (len(text) >= max):
inv = max * 10
print("Reducing length of chat history... This can be a bit buggy.")
nl = text[inv:]
text = re.search(r'(?<=\n)[\s\S]*', nl).group(0)
return text
else:
return text
def ask(username, botname, question, chat_log=None):
if chat_log is None:
chat_log = 'The following is a chat between two users:\n\n'
now = datetime.now()
ampm = now.strftime("%I:%M %p")
t = '[' + ampm + '] '
prompt = f'{chat_log}{t}{username}: {question}\n{t}{botname}:'
response = completion.create(
prompt=prompt, engine="text-curie-001", stop=['\n'], temperature=0.7,
top_p=1, frequency_penalty=0, presence_penalty=0.6, best_of=3,
max_tokens=500)
answer = response.choices[0].text.strip()
return answer
# fp = 15 pp= 1 top_p = 1 temp = 0.9
def append_interaction_to_chat_log(username, botname, question, answer, chat_log=None):
if chat_log is None:
chat_log = 'The following is a chat between two users:\n\n'
chat_log = limit(chat_log, max)
now = datetime.now()
ampm = now.strftime("%I:%M %p")
t = '[' + ampm + '] '
return f'{chat_log}{t}{username}: {question}\n{t}{botname}: {answer}\n'
def interact(bot, update, botname, username, new):
global chat_log
global cache
global qcache
print("==========START==========")
tex = update.message.text
text = str(tex)
analyzer = SentimentIntensityAnalyzer()
if new != True:
vs = analyzer.polarity_scores(text)
if debug == True:
print("Sentiment of input:\n")
print(vs)
if vs['neg'] > 1:
update.message.reply_text('Can we talk something else?')
return
if new == True:
if debug == True:
print("Chat_LOG Cache is...")
print(cache)
print("Question Cache is...")
print(qcache)
chat_log = cache
question = qcache
if new != True:
question = text
qcache = question
cache = chat_log
#update.message.reply_text('Computing...')
try:
answer = ask(username, botname, question, chat_log)
if debug == True:
print("Input:\n" + question)
print("Output:\n" + answer)
print("====================")
stripes = answer.encode(encoding=sys.stdout.encoding,errors='ignore')
decoded = stripes.decode("utf-8")
out = str(decoded)
vs = analyzer.polarity_scores(out)
if debug == True:
print("Sentiment of output:\n")
print(vs)
if vs['neg'] > 1:
update.message.reply_text('I do not think I could provide you a good answer for this. Use /retry to get positive output.')
return
update.message.reply_text(out)
chat_log = append_interaction_to_chat_log(username, botname, question, answer, chat_log)
if debug == True:
#### Print the chat log for debugging
print('-----PRINTING CHAT LOG-----')
print(chat_log)
print('-----END CHAT LOG-----')
except Exception as e:
print(e)
errstr = str(e)
update.message.reply_text(errstr)
def error(bot, update):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update)
def main():
"""Start the bot."""
updater = Updater(tgkey, use_context=False)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("reset", reset))
dp.add_handler(CommandHandler("retry", retry))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, runn))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()