-
Notifications
You must be signed in to change notification settings - Fork 0
/
namebot5.3.py
executable file
·416 lines (375 loc) · 15.8 KB
/
namebot5.3.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###5.2 changelogs
#added a new bot to botfather called coolnamebotbeta so i can run local instances of testing versions while also allownig the prod version to go on.
#done
#add "scream method" which will look for a debug variable and wither output to Telegram or to the terminal depending on the situation.
#done but not needed since im using the beta bot
#TODO alter debug so that it does not contact the bot at all
#this is no longer needed since I can use the betabot
#for this I will need another method to make sure input can be taken on the command line?
# we would set debug when working on the bot and if we did not want our output to be sent to the bot
#done
#remove the "name list" mention from /help. this is handled by /list now
#done
###5.3 changelogs
#suggestions
#move large functions to new files
#Stats
#list things like:
#uptime,
#number of names held
#recent changes
#maybe something specific to the users
#like a personalized "thanks matt, adding $name"
#start the name rating system
#needs a backend score
#needs a way to compare names
#needs a way to show the higher ranked names
#needs a way to rate names
#maybe a hot or not "is john cooler than steven" with three options
#changes:
#add a random name selection - done
#allow a letter to be specified for a random name starting with "g"
#TODO
#maybe allow to specify a number also, "/random g 4" would show 4 names starting with g
#TODO?
#probably could do a "if var1 == 1-100 or var2 == 1-100 that way /list random g 4 and /list random 4 g would both work
#change /list behavior
#it will prompt the user to add a letter
#and will print 10 random names
#remove /list random function, /list is random enough -done kept in code but removed from help
#add /list 4 -done between 1 and 100 names
#edit help to reflect the new list machanic - done
##INSTALLING: sudo pip install python-telegram-bot --upgrade
##also needs python3
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
##TODO alter the add method to always update a database, \
## alter the save method to sort, merge, etc the temp db and a long term one,
## including archiving the old ersion and making a new one
#do your imports
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import os
#used for random name selection
import random
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
debugtoggle=0
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def scream(bot,update,string):
# if debugtoggle==0:
# update.message.reply_text(string)
# if debugtoggle==1:
# print(string)
update.message.reply_text(string)
def main():
#load names
##short for testing
open_file = open('names.db.new', 'r')
##long for later
##open_file = open('names.db.new', 'r')
global all_names
all_names = open_file.readlines()
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
if debugtoggle==0:
file=open('apitoken.txt','r')
else:
file=open('apitokenbeta.txt','r')
filetoken=file.readline()
token=str(filetoken).rstrip("\n\r")
updater = Updater(token)
global names
names=["this","that"]
# 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("echo", echo))
dp.add_handler(CommandHandler("name", name))
dp.add_handler(CommandHandler("load", load))
dp.add_handler(CommandHandler("save", save))
dp.add_handler(CommandHandler("add", add))
dp.add_handler(CommandHandler("list", list))
# on noncommand i.e message - echo the message on Telegram
#dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
def start(bot, update):
"""Send a message when the command /start is issued."""
##update.message.reply_text('Hi!')
scream(bot,update,'Hi!')
def help(bot, update):
##TODO seperate the list into seperate lines
"""Send a message when the command /help is issued."""
#update.message.reply_text('I can do a few things.\n'
# 'Let me know cool names with "/name somename" \n'
# ' "/name add NAME" #will add the name to our database\n '
# '/help" will print this menu\n'
# ' "/echo words words words" #is as close to talking as i get \n '
# '"/list" will list the names and "/list e" will list all the names staring with "e"')
#
scream(bot,update,'I can do a few things.\n'
'Let me know cool names with "/name somename" \n'
' "/name add NAME" #will add the name to our database\n '
'"/name print" #will print the names in our database\n"'
'/help" will print this menu\n'
' "/echo words words words" #is as close to talking as i get \n '
'"/list" will list 10 random names and "/list e" will list all the names staring with "e"\n'
'"/list 13" will list whatever number of names up to 100\n'
)
def getRandom(list):
name = "noodle"
#print("size is " + str(len(list)))
templength=len(list)
randomchoice=random.randrange(0,templength-1)
#print("random is " + str(randomchoice))
namechoice=str(list[randomchoice])
#print("random index name is " + str(list[randomchoice]))
#print(list[0] + list[466-1])
return namechoice
def list(bot,update):
##TODO: list a different message if no names are found under a letter
##TODO: possibly change /name add to /add
#This shouldo probably not have the first name addded immediately
#sort the names without seperating capital and lower case.
sorted_names = sorted(all_names, key=str.lower)
#start the list and message no change the first name will be a duplicate
message = str(sorted_names[0])
message_letter = str()
previous = [sorted_names[0]]
#print(previous)
#print(all_names[0])
#print(all_names)
##Get letter to list specific names below
#format
temp = update.message.text
temp = temp.split(' ')
#print(temp)
#set first argument to hopefully a letter
#print(len(temp))
if len(temp) > 1:
letter=str(temp[1])
else:
letter="0"
previous = [sorted_names[0]]
#print("temp is :" + str(letter))
if letter == "random":
#print("you said random?")
#print("names are: " + str(sorted_names))
scream(bot,update,getRandom(sorted_names))
#if they selected a letter
elif letter.isalpha() and len(letter) == 1:
if previous[0][0] == letter.upper() or previous[0][0] == letter.lower():
message_letter = message_letter + str(previous[0]).capitalize()
#print(message_letter)
#print("LETTER: " + letter)
for name_temp in sorted_names:
n = name_temp.lower()
#print("first letter of " + n + " is " + n[0])
if n[0] == letter.lower() or n[0] == letter.upper():
#print(n + " matches letter")
# print("preparing " + str(n))
dupe = 0
for p_temp in previous:
p = p_temp.lower()
# print("p is " + str(p))
if n.lower() == p.lower():
# print("I found dupe" + str(n) + " " + str(p))
dupe = 1
break
# if nothing fails
if dupe == 0:
previous.append(n.lower())
message_letter = message_letter + n.capitalize()
# print(previous)
# print("finished " + str(n) + " the list is " + str(previous))
#update.message.reply_text("Names starting with " + letter + ":\n" + message_letter)
scream(bot,update,"Names starting with " + letter + ":\n" + message_letter)
# print all names without any duplicates.
# n*n checks for duplicates and if nothing matches adds it to the output.
##TODO: sort output perhaps
elif letter.isnumeric and int(letter) > 0:
print("this is a number")
print(letter)
if int(letter) > 0 and int(letter) <= 300:
print("your terms are acceptable")
tempmessage=str("here are your " + letter + " names\n")
for i in range(0,int(letter)):
tempmessage=tempmessage + str(getRandom(sorted_names))
message=str(tempmessage)
scream(bot,update,message)
else:
tempmessage="that is a big number, here is 5\n"
number=5
for i in range(0,number):
tempmessage=tempmessage + str(getRandom(sorted_names))
message=str(tempmessage)
scream(bot,update,message)
else:
number=10
tempmessage="Here is a few random names, use 'list d' to list all names starting with d\n"
for i in range(0,number):
tempmessage=tempmessage + str(getRandom(sorted_names))
message=str(tempmessage)
# for name_temp in sorted_names:
# #print(u"name_temp is " + (name_temp))
# n = name_temp
# #print("preparing " + str(n))
# dupe = 0
# for p in previous:
# #print("p is " + str(p))
# if n.lower() == p.lower():
# #print("I found dupe" + str(n) + " " + str(p))
# dupe = 1
# break
# #else:
# #print("i found a not dupe " + str(n))
# # if nothing fails
# if dupe == 0:
# #print("n is " + str(n))
# previous.append(n)
# message = message + n.capitalize()
# #print(previous)
# #print("finished " + str(n) + " the list is " + str(previous))
# #update.message.reply_text(message)
scream(bot,update,message)
##Old method:
# i=0
# previous=[str(all_names[0])]
# while i < len(all_names):
# comp=[all_names[i]]
# print(all_names[i])
###check for duplicate names
# j = 0
# dupe=0
# while j <= len(previous):
# print(j)
# #print(comp[0])
# #print(comp)
# #print(str(comp[0]))
# #print(previous)
# #print(previous[0])
# #print(str(previous[j]))
# #print("length of previous is " + str(len(previous)))
# print("comparing \"" + comp[0] + "\" to \"" + previous[j] + "\"")
# if comp[0] == previous[j]:
# print("duplicate name" + str(comp[0]))
# dupe=1
# j = j + 1
# break
# else:
# print(str(previous[j])+ "not duplicate name " + str(comp[0]))
# previous = previous + comp
# #This was causing messages to be duplicated
# #message = message + all_names[i]
# j = j + 1
# if dupe == 0:
# message= message + all_names[i]
# i = i + 1
# print("i is now " + str(i))
# print(message)
# update.message.reply_text(message)
def echo(bot, update):
"""Echo the user message."""
temp=update.message.text
temp=temp.split(' ')
#update.message.reply_text("temp is " + str(temp))
#update.message.reply_text("did you say " + temp[1] + "?")
scream(bot,update,"did you say " + temp[1] + "?")
def add(bot, update, inputtemp="NULL"):
global names
global all_names
if inputtemp != "NULL":
temp=[inputtemp + "\n"]
print(temp)
print(inputtemp)
all_names = all_names + temp
scream(bot,update,str(temp[0].strip("\n\r")) + " added")
save(bot,update)
else:
temp=update.message.text
temp=temp.split(' ')
print(temp)
temp=[temp[1] + "\n"]
print(temp)
all_names = all_names + temp
scream(bot,update,str(temp[0].strip("\n\r")) + " added")
save(bot,update)
def name(bot, update):
##Todo: refactor so that the second argument is always checked, and subfunctions run from there
##todo: print names on individual lines
##todo: load a database file
##todo: save to a database file
##todo: add case for a single argument ie "/name" where it posts help?
global names
global all_names
#update.message.reply_text(update.message.text + " is a great name")
temp=update.message.text
temp=temp.split(' ')
#update.message.reply_text("temp is " + str(temp))
if temp[1] == "add" and len(temp) == 3:
add(bot,update,temp[2])
# temp2 = [temp[2] + "\n"]
# #names = names + temp2
# all_names = all_names + temp2
# #update.message.reply_text(str(temp[2]) + " added")
# scream(bot,update,str(temp[2]) + " added")
# # print(str(temp[2]) + " added")
# save(bot,update)
elif temp[1] == "print":
list(bot,update)
else:
if len(temp) == 2:
#update.message.reply_text(temp[1] + " is a great name")
scream(bot,update,temp[1] + " is a great name")
else:
#update.message.reply_text("I dont get it")
scream(bot,update,"I dont get it")
# if temp[1] == "add":
# update.message.reply_text("you want to add")
# temp2 = [temp[2]]
# update.message.reply_text("temp2 is " + str(temp2) + "names is " + str(names) + "adding now")
# ##names = names + temp2
# update.message.reply_text("temp2 is " + str(temp2) + "names is " + str(names))
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
#This is basically depricated/not in use at this time
def load(bot, update):
#"""Echo the user message."""
#temp=update.message.text
#temp=temp.split(' ')
#update.message.reply_text("temp is " + str(temp))
update.message.reply_text(" this will load the database into memory but it is in todo status" )
#This is basically depricated/not in use at this time
def save(bot, update):
#update.message.reply_text("updating database" )
global all_names
with open('names.db.new','w') as f:
for item in all_names:
f.write("{}".format(item))
#update.message.reply_text("database updated")
if __name__ == '__main__':
main()