forked from C64Axel/MonsterBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtgbot.py
318 lines (271 loc) · 8.8 KB
/
mtgbot.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
#!/usr/bin/env python
import telepot
import pymysql.cursors
import logging
import sys
import json
from telepot.loop import MessageLoop
from time import sleep
from configobj import ConfigObj
from lib.dbcheck import db_need_update
from lib.logfile import log
def sendtelegram(chatid,msg):
try:
bot.sendMessage(chatid, msg)
except:
log ("ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid),"user")
# Handle for incomming Commands
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'location':
latitude = msg['location']['latitude']
longitude = msg['location']['longitude']
chatid = msg['from']['id']
try: # insert user location
cursor.execute("update user set latitude ='%s', longitude = '%s', distance = 5 where chatid = '%s'" % (latitude,longitude,chatid))
sendtelegram(chat_id, msg_loc["23"].format(str(latitude),longitude))
except:
sendtelegram(chat_id,msg_loc["24"])
pass
return
elif content_type != 'text':
return
fromwho = msg.get('from')
username = fromwho.get('username', '')
vname = fromwho.get('first_name', '')
nname = fromwho.get('last_name', '')
log("Message from ID: {}:{}:{}".format(str(chat_id),username,msg['text']),"user")
command = msg['text'].split("@")[0].split(" ")[0]
try:
connection.ping(reconnect=True)
cursor.execute("select count(*) from userblock where chatid = '%s'" % (chat_id))
result = cursor.fetchone()
if result[0] == 1:
sendtelegram(chat_id,msg_loc["19"])
command=""
except:
sendtelegram(chat_id,msg_loc["6"])
command=""
if command == "/help":
msg = ""
helplist = msg_loc["1"].split("\n")
for i in helplist:
msg = msg + "{} :\n{}\n".format(i.split(":")[0],i.split(":")[1])
bot.sendMessage(chat_id, msg)
elif command == "/start":
msg = ""
startmsg = open(invstartmsg, "r")
for line in startmsg:
msg = msg + "{}".format(line)
sendtelegram(chat_id,msg)
startmsg.close()
try: # delete chatid from Stop Table
cursor.execute("delete from userstop where chatid = '%s'" % (chat_id))
except:
pass
try: # insert users information and the bot id
cursor.execute("insert into user values ('%s','%s','%s','%s','%s',NULL,NULL,NULL,'0',current_timestamp)" % (botid,username,vname,nname,chat_id))
except:
pass
sendtelegram(chat_id,msg_loc["2"])
elif command == "/stop":
try: # delete user data
cursor.execute("delete from user where botid = '%s' and chatid = '%s'" % (botid,chat_id))
except:
pass
try: # and if no bot left insert chatid in stop table for reorg
cursor.execute("select count(*) from user where chatid = '%s'" % (chat_id))
result = cursor.fetchone()
if result[0] == 0:
cursor.execute("insert ignore into userstop values ('%s', CURRENT_TIMESTAMP)" % (chat_id))
except:
pass
sendtelegram(chat_id,msg_loc["3"])
elif command == "/status": # send user staus of his bot
cursor.execute("select count(*) from user where botid = '%s' and chatid = '%s'" % (botid,chat_id))
result = cursor.fetchone()
if result[0] > 0:
sendtelegram(chat_id,msg_loc["4"])
else:
sendtelegram(chat_id,msg_loc["5"])
elif command == "/mydata": # send users stored information
cursor.execute("select botid,username,vorname,nachname,chatid,latitude,longitude,distance,pvponly from user where chatid = '%s'" % (chat_id))
result = cursor.fetchall()
if result:
for row in result:
cursor.execute("select botname from bot where botid = '%s'" % (row[0]))
botname = cursor.fetchone()
msg = str(msg_loc["21"].format(row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8]))
sendtelegram(chat_id,msg)
else:
sendtelegram(chat_id,msg_loc["22"])
elif command == "/deleteall": # delete user completely
cursor.execute("delete from userassign where chatid = '%s'" % (chat_id))
cursor.execute("delete from user where chatid = '%s'" % (chat_id))
cursor.execute("delete from userstop where chatid = '%s'" % (chat_id))
sendtelegram(chat_id,msg_loc["20"])
elif command == "/list": # list monsterlist to user
cursor.execute("select pkmnid,iv from userassign where chatid = '%s'" % (chat_id))
result_p = cursor.fetchall()
msg = str(msg_loc["16"]) + "\n"
for row in result_p:
msg = msg + "{} : {} : {}\n".format(row[0],pkmn_loc[str(row[0])]["name"],row[1])
while len(msg) > 0: # cut message to telegram max messagesize
msgcut = msg[:4096].rsplit("\n",1)[0]
sendtelegram(chat_id, msgcut)
msg = msg[len(msgcut)+1:]
elif command == "/add": # add Pokemon to list
pkmniv = 0
try:
pkmnid = msg['text'].split(" ")[1]
except:
sendtelegram(chat_id,msg_loc["7"] + "/add")
return
try:
pkmniv = int(msg['text'].split(" ")[2])
except:
pass
if pkmniv > 100:
pkmniv = 100
if pkmniv < -1:
pkmniv = -1
try:
pkname = pkmn_loc[str(pkmnid)]["name"]
try:
cursor.execute("insert into userassign values ('%s','%s','%s')" % (pkmnid,chat_id,pkmniv))
sendtelegram(chat_id, pkname + msg_loc["8"])
except:
sendtelegram(chat_id, pkname + msg_loc["9"])
except:
sendtelegram(chat_id, str(pkmnid) + msg_loc["10"])
elif command == "/del": # delete Pokemon from list
try:
pkmnid = msg['text'].split(" ")[1]
except:
sendtelegram(chat_id,msg_loc["7"] + "/del")
return
try:
pkname = pkmn_loc[str(pkmnid)]["name"]
if cursor.execute("delete from userassign where chatid = '%s' and pkmnid = '%s'" % (chat_id,pkmnid)):
sendtelegram(chat_id, pkname + msg_loc["12"])
else:
sendtelegram(chat_id, pkname + msg_loc["13"])
except:
sendtelegram(chat_id, str(pkmnid) + msg_loc["10"])
elif command == "/setiv": # set IV to Pokemon
try:
pkmnid = int(msg['text'].split(" ")[1])
pkmniv = int(msg['text'].split(" ")[2])
except:
sendtelegram(chat_id, msg_loc["14"])
return
if pkmniv > 100:
pkmniv = 100
try:
pkname = pkmn_loc[str(pkmnid)]["name"]
if cursor.execute("update userassign set iv = '%s' where chatid = '%s' and pkmnid = '%s'" % (pkmniv,chat_id,pkmnid)):
sendtelegram(chat_id, msg_loc["15"].format(str(pkmniv),pkname))
else:
sendtelegram(chat_id, pkname + msg_loc["13"])
except:
sendtelegram(chat_id, str(pkmnid) + msg_loc["10"])
elif command == "/delpos": # delete User Position
chatid = msg['from']['id']
try:
cursor.execute("update user set latitude = NULL, longitude = NULL, distance = NULL where chatid = '%s'" % (chatid))
sendtelegram(chat_id, msg_loc["25"])
except:
sendtelegram(chat_id,msg_loc["26"])
return
elif command == "/distance": # radius anpassen
chatid = msg['from']['id']
try:
distance = msg['text'].split(" ")[1]
except:
sendtelegram(chat_id,msg_loc["29"])
return
try:
cursor.execute("update user set distance = '%s' where chatid = '%s'" % (distance,chatid))
sendtelegram(chat_id,msg_loc["27"])
except:
sendtelegram(chat_id,msg_loc["28"])
return
elif command == "/pvponly": # pvp only mode
chatid = msg['from']['id']
try:
pvponly = msg['text'].split(" ")[1]
except:
sendtelegram(chat_id,msg_loc["30"])
return
try:
cursor.execute("update user set pvponly = '%s' where chatid = '%s'" % (pvponly,chatid))
sendtelegram(chat_id,msg_loc["31"])
except:
sendtelegram(chat_id,msg_loc["32"])
return
else:
if command[:1] == '/':
sendtelegram(chat_id, command + msg_loc["17"])
### _MAIN_ ###
def my_excepthook(excType, excValue, traceback, logger=logging):
logging.error("Logging an uncaught exception",
exc_info=(excType, excValue, traceback))
sys.excepthook = my_excepthook
logname="user"
# read inifile
try:
config = ConfigObj("config.ini")
token=config.get('token')
db = config['dbname']
dbhost = config['dbhost']
dbport = config.get('dbport', '3306')
dbuser = config['dbuser']
dbpassword = config['dbpassword']
locale = config.get('locale', 'de')
invstartmsg = config.get('startmsg', "locales/startmsg_" + locale + ".txt")
except:
log("Error in config.ini",logname)
quit()
# connect to database
#
try:
connection = pymysql.connect(
host=dbhost,
user=dbuser,
password=dbpassword,
db=db,
port=int(dbport),
charset='utf8mb4',
autocommit='True')
cursor = connection.cursor()
except:
log("can not connect to database","user")
quit()
if db_need_update(cursor):
log("Your DB-Version is to low. Please start dbupdate.py first","user")
quit()
# get bot information
#
bot = telepot.Bot(token)
try:
botident = bot.getMe()
botname = botident['username']
botcallname = botident['first_name']
botid = botident['id']
try:
cursor.execute("insert into bot values ('%s','%s')" % (botid,botname))
except:
pass
except:
log("Error in Telegram. Can not find Botname and ID","user")
quit()
pkmn_loc = json.load(open("locales/monster_" + locale + ".json"))
msg_loc = json.load(open("locales/msg_" + locale + ".json"))
# Main Loop
try:
MessageLoop(bot, handle).run_as_thread()
log("Bot {} started".format(botname),"user")
while True:
sleep(60)
except KeyboardInterrupt:
pass