-
Notifications
You must be signed in to change notification settings - Fork 0
/
namebot5.py
executable file
·284 lines (245 loc) · 9.92 KB
/
namebot5.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##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
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# 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 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.
file=open('apitoken.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("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!')
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 '
'"/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 the names and "/list e" will list all the names staring with "e"')
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"
#if they selected a letter
previous = [sorted_names[0]]
if 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)
# print all names without any duplicates.
# n*n checks for duplicates and if nothing matches adds it to the output.
##TODO: sort output perhaps
else:
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)
##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] + "?")
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
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:
temp2 = [temp[2] + "\n"]
#names = names + temp2
all_names = all_names + temp2
update.message.reply_text(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")
else:
update.message.reply_text("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)
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" )
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()