-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.py
261 lines (211 loc) · 9.17 KB
/
bot.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
"""
References:
https://core.telegram.org/bots/api
https://python-telegram-bot.readthedocs.io/en/latest
"""
import datetime
import time
import telegram
from threading import Thread, Timer
from settings import TOKEN, msg_flood, msg_interval, botName
from telegram.ext import Updater, MessageHandler, Filters, CommandHandler, CallbackQueryHandler
from sys import exit
from db_handler import MySQL_DB
import random
import logging
from systemd.journal import JournaldLogHandler
db = MySQL_DB()
logger = logging.getLogger(botName)
journald_handler = JournaldLogHandler()
journald_handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
logger.addHandler(journald_handler)
logger.setLevel(logging.DEBUG)
flood_counter = []
data = []
flood_data={}
def on_new_animation(bot, update):
logger.info("[!][on_new_animation]")
chat_id = update.message.chat_id
user_id = update.message.from_user.id
msg_id = update.message.id
try:
item = "{}:{}:{}".format(chat_id, user_id, msg_id)
logger.info("[!][New Animation] {}".format(item))
data.append(item)
flood_counter.append(item)
flood_data[chat_id][user_id].append(msg_id)
check_flood(bot, update)
Timer(msg_interval, timeout, [bot, update]).start()
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def deleteMsgs(bot, update, msgIDs):
logger.info("[!][deleteMsgs]")
try:
chat_id = str(update.message.chat_id)
user_id = str(update.message.from_user.id)
for msg in msgIDs[msg_flood:]:
Thread(target=deleteMsg, args=(bot, update, int(msg),),).start()
item = "{}:{}:{}".format(update.message.chat_id, update.message.from_user.id, msg)
data.remove(item)
xinga(bot, update)
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def xinga(bot, update):
logger.info("[!][xinga]")
try:
query = "SELECT text FROM xingamento ORDER BY RAND() LIMIT 1"
row = db.fetchone(query)
quote = "__{}__".format(row[0])
msg = "[!] Cala a boca {}, {}!".format(update.message.from_user.first_name, quote)
bot.send_message(update.message.chat_id, msg, parse_mode='Markdown')
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def deleteMsg(bot, update, msgId):
logger.info("[!][deleteMsg]")
try:
chat_id = update.message.chat_id
logger.info("[!][deleteMsg] Deleting = > {}".format(msgId))
bot.delete_message(chat_id=chat_id, message_id=msgId)
item = "{}:{}:{}".format(update.message.chat_id, update.message.from_user.id, msgId)
data.remove(item)
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def check_flood(bot, update):
logger.info("[!][check_flood]")
try:
chat_id = str(update.message.chat_id)
user_id = str(update.message.from_user.id)
counter = 0
# msgIds = []
logger.info("[!] Checking flood")
for i, item in enumerate(flood_counter):
if (chat_id + ":" + user_id) in item:
# msgIds.append((flood_counter[i].split(":")[2]))
counter += 1
if counter > msg_flood:
logger.info("[!] Flood in action: {} ({})".format(user_id, counter))
# Thread(target = deleteMsg, args = (bot, update, update.message.message_id), ).start()
deleteMsg(bot, update, update.message.message_id)
# deleteMsgs(bot, update, msgIds)
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def timeout(bot, update):
logger.info("[!][timeout]")
try:
logger.info("[!] timeout - flood_counter: {}".format(flood_counter))
logger.info("[!] timeout - data: {}".format(data))
item = "{}:{}:{}".format(update.message.chat_id, update.message.from_user.id, update.message.message_id)
flood_counter.remove(item)
# data.remove(item)
except Exception as e:
loggaer.info(str(e))
def logging(bot, update):
try:
photo = ""
query = ("INSERT INTO log (message_id, date, chat_id, text, photo, from_id, first_name, last_name, username) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')").format(update.message.message_id, str(update.message.date), update.message.chat.id, str(update.message.text), photo, update.message.from_user.id, update.message.from_user.first_name, update.message.from_user.last_name, update.message.from_user.username)
# else:
# photo = update.message.photo.file_id
#logger.info(photo)
# logger.info(query)
db.execute(query)
logger.info("{}:{}:{}".format(update.message.chat.id, update.message.from_user.first_name, update.message.text))
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def put_quote(bot, update):
logger.info("[!][put_quote]")
try:
message_id = update.message.reply_to_message.message_id
query = ("INSERT INTO quote (message_id, chat_id) VALUES ('{}', '{}')").format(message_id, update.message.chat_id)
db.execute(query)
logger.info("{} - OK".format(db.cursor.lastrowid))
bot.send_message(update.message.chat.id, "Salvei \"{}\" com id {}".format(update.message.reply_to_message.text, db.cursor.lastrowid))
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def get_quote(bot, update):
logger.info("[!][get_quote]")
print("[!][get_quote]")
try:
if update.message.text == "/lauters":
query = "SELECT text FROM lauters ORDER BY RAND() LIMIT 1"
else:
quote_id = (update.message.text).split(" ")
if len(quote_id) > 1:
query = "SELECT message_ID FROM quote WHERE chat_ID = {} AND id = {} ORDER BY RAND() LIMIT 1".format(update.message.chat_id, int(quote_id[1]))
else:
query = "SELECT message_ID FROM quote WHERE chat_ID = {} ORDER BY RAND() LIMIT 1".format(update.message.chat_id)
message_id = db.fetchone(query)
query = "SELECT text FROM log WHERE message_id = {}".format(message_id[0])
row = db.fetchone(query)
quote = "__{}__".format(row[0])
# logger.info(quote)
bot.send_message(update.message.chat_id, quote, parse_mode='Markdown')
except Exception as e:
logger.exception(str(e))
sys.exit(1)
# logger.info(row)
def list_quotes(bot, update):
print("[!] list_quotes")
quotes_list = ""
try:
query = "SELECT quote.id, log.text FROM quote, log WHERE quote.chat_id = {} AND quote.message_id=log.message_id".format(update.message.chat_id)
results = db.fetchall(query)
for result in results:
quotes_list += "#{}: {} \n".format(result[0], result[1])
bot.send_message(update.message.from_user.id, quotes_list)
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def call_bot(bot, update):
logger.info("[!] call_bot")
try:
msg = ("Quer falar em particular comigo?\n")
start_bot_keyboard = [[telegram.InlineKeyboardButton(text='Siiiiiiiim, seu lindo!', url="https://t.me/{}?start=payload".format(botName))]]
reply_kb_markup = telegram.InlineKeyboardMarkup(start_bot_keyboard, resize_keyboard=True, one_time_keyboard=True)
bot.send_message(update.message.chat_id, msg, reply_markup=reply_kb_markup)
except Exception as e:
logger.exception(str(e))
sys.exit(1)
def start_bot(bot, update):
try:
msg = ("Aqui está a lista de comandos que você pode usar no grupo:\n")
msg += ("/save: Responder uma mensagem com **/save** vai salva-la\n")
msg += ("/help: Pra iniciar essa conversa (e eu poder falar em particular com você)\n")
msg += ("/quote: Vai trazer uma frase aleatória que foi salva anteriormente\n")
msg += ("/quote X: Vai trazer a frase número X\n")
msg += ("/lauters: Traz uma frase do Lawto\n")
msg += ("/list: Mostro pra você todas as frases salvas e seus respectivos números")
bot.send_message(update.message.from_user.id, msg, parse_mode='Markdown')
except Exception as e:
logger.exception(str(e))
sys.exit(1)
try:
updater = Updater(token=TOKEN)
dp = updater.dispatcher
log_handler = MessageHandler(Filters.all, logging)
flood_handler = MessageHandler(Filters.animation | Filters.photo | Filters.video, on_new_animation)
save_handler = CommandHandler("save", put_quote)
start_handler = CommandHandler("start", start_bot)
callbot_handler = CommandHandler("help", call_bot)
quote_handler = CommandHandler("quote", get_quote)
lauters_handler = CommandHandler("lauters", get_quote)
list_quotes_handler = CommandHandler("list", list_quotes)
dp.add_handler(list_quotes_handler)
dp.add_handler(save_handler)
dp.add_handler(start_handler)
dp.add_handler(callbot_handler)
dp.add_handler(quote_handler)
dp.add_handler(lauters_handler)
dp.add_handler(flood_handler)
dp.add_handler(log_handler)
updater.start_polling()
updater.idle()
except Exception as e:
logger.exception(str(e))
sys.exit(1)