forked from 91DarioDev/TelegramPositionBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
275 lines (243 loc) · 9.39 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import botogram
import json
import time
import sqlite3
import urllib.request
from database import *
from extrafeatures import *
from config import *
bot = botogram.create(token)
bot.owner = your_name
bot.about = description
#start checking positions
def boot(bot):
check(playstore_parse(), "playstore")
check(appstore_parse(), "appstore")
#check if an error occurred (the html of the pages changed),
#telegram is not in the leaderboard etc or send notifications
def check(x, store):
if x==False:
#send the message to the owner an error occured
bot.chat(owner).send("an error occurred on "+str(store))
else:
posizione=x
cfr_p=cfr(store)
if cfr_p!=posizione:
final(posizione, store)
#check the position on appstore
def playstore_parse():
link = "https://play.google.com/store/apps/collection/topselling_free?gl=it"
request = urllib.request.urlopen(link)
page = request.read()
page=page.decode(encoding='UTF-8')
stringa="href=\"/store/apps/details?id=org.telegram.messenger\" aria-label="
if stringa in page:
posizione=page[page.find(stringa):].split()[2]
if posizione.endswith("."):
while "." in posizione:
posizione=posizione.replace(".","")
posizione=int(posizione)
return (posizione)
#send and advice to the owner if the string doesn't end with the dot. something changed
else:
return False
#send an advice to the owner if the string isn't in the file.
else:
return False
#check the position on appstore
def appstore_parse():
link = "http://www.apple.com/it/itunes/charts/free-apps/"
request = urllib.request.urlopen(link)
page = request.read()
stringa="Telegram Messenger"
if stringa in str(page):
posizione=str(page)[:str(page).find(stringa)].split("</strong>")[-2]
posizione=posizione[str(posizione).find("<strong>")+8:]
if posizione.endswith("."):
while "." in posizione:
posizione=posizione.replace(".","")
posizione=int(posizione)
return (posizione)
#send and advice to the owner if the string doesn't end with the dot. something changed
else:
return False
#send an advice to the owner if the string isn't in the file.
else:
return False
#check last records to compare
def cfr(x):
c.execute("SELECT posizione FROM %s ORDER BY id DESC LIMIT 1" % (x,))
cfr=c.fetchone()[0]
return (cfr)
#get a list of notification subscribed users
def subscribed():
c.execute("SELECT id FROM chat WHERE iscritto=1")
lista_chat=(c.fetchall())
return (lista_chat)
#save new records in DB and send the notification to anyone (subscribed)
def final(posizione, store):
lista_chat=subscribed()
cfr2=cfr(store)
if store=="appstore":
emoji="\U0001F34E"
if store=="playstore":
emoji="\U0001F916"
variazione=""
somma=(int(cfr2)-int(posizione))
if somma<0:
variazione+=str(somma)+ "\U0001f53d"
start="<i>"
end="</i>"
if somma>0:
variazione+="+"+str(somma)+ "\U0001f53c"
start="<b>"
end="</b>"
c.execute("INSERT INTO %s(posizione) VALUES(?)" % (store,),(posizione,))
conn.commit()
for chat_singola in lista_chat:
chat_singola=(chat_singola)[0]
try:
bot.chat(chat_singola).send(emoji+start+"-"+str(store)+": "+str(posizione)+"\n "+variazione+end, syntax="html")
#delete from the DB chats no more active
except botogram.ChatUnavailableError:
c.execute("DELETE FROM chat WHERE id=?",(chat_singola,))
conn.commit()
except botogram.APIError:
c.execute("DELETE FROM chat WHERE id=?",(chat_singola,))
conn.commit()
time.sleep(0.4)
#start the check every x seconds
@bot.timer(1800)
def start(bot):
boot(bot)
#add users texting with the bot to the DB
@bot.before_processing
def add_chats_to_db2(chat, message):
add_chats_to_db(chat, message)
#get a backup of the DB
@bot.command("database", hidden=True)
def backup_database2(chat, message, args):
if message.sender.id==owner:
backup_database(chat, message, args)
#send last records
@bot.command("posizioniattuali")
def posizioni_attuali(chat, message, args):
"""
Posizioni attuali
"""
chat.send("<b>playstore:</b> "+str(actual_position("playstore"))+"\n<b>appstore:</b> "+str(actual_position("appstore")), syntax="html")
#send the average of the positions
@bot.command("media")
def medium(chat, message, args):
"""
mostra la media tra tutte le posizioni loggate
"""
chat.send("<b>playstore:</b> "+str(the_3_stats("AVG","playstore"))+"\n<b>appstore:</b> "+str(the_3_stats("AVG","appstore")), syntax="html")
#send the best position
@bot.command("migliore")
def maximum(chat, message, args):
"""
mostra la posizione migliore mai raggiunta
"""
chat.send("<b>playstore:</b> "+str(the_3_stats("MIN","playstore"))+"\n<b>appstore:</b> "+str(the_3_stats("MIN","appstore")), syntax="html")
#send the lower position
@bot.command("peggiore")
def minimum(chat, message, args):
"""
mostra la posizione peggiore mai raggiunta
"""
chat.send("<b>playstore:</b> "+(str(the_3_stats("MAX","playstore")))+"\n<b>appstore:</b> "+(str(the_3_stats("MAX","appstore"))), syntax="html")
#send the hystory of logs
@bot.command("logsappstore")
def storico_appstore(chat, message, args):
"""
mostra uno storico delle posizioni su appstore
"""
hystory(chat, message, args, "appstore")
#send the hystory of logs
@bot.command("logsplaystore")
def storico_playstore(chat, message, args):
"""
mostra uno storico delle posizioni su playstore
"""
hystory(chat, message, args, "playstore")
#get a stat of chats using the bot
@bot.command("chat", hidden=True)
def numero_chat(chat, message, args):
if message.sender.id==owner:
chat.send(stats_message())
#enable notifications
@bot.command("getnotification")
def yes_notif(chat, message, args):
"""
Riattiva i messaggi per le variazioni di posizioni
"""
notif(chat, message, args, 1)
#a message you have been subscribed to notifications
message.reply("<b>Iscritto!</b> Ora riceverai messaggi per le variazioni di posizioni. Se non vuoi: /stopupdate.", syntax="html")
#disable notifications
@bot.command("stopnotification")
def no_notif(chat, message, args):
"""
Riattiva i messaggi per le variazioni di posizioni
"""
notif(chat, message, args, 0)
#a message you disabled notifications
message.reply("<b>Disiscritto!</b> Potrai continuare a usare il bot senza doverlo bloccare, non ricevendo più le \
notifiche. Se ci ripensi /getupdate", syntax="html")
#send a broadcast to every user
@bot.process_message
def broadcast2(chat, message, bot):
if message.text:
if message.sender.id==owner and message.text.startswith("broadcast->"):
broadcast(chat, message, bot)
#get a preview of the broadcast you would like to send
@bot.process_message
def preview(chat, message):
if message.text:
if message.sender.id==owner and message.text.startswith("preview->"):
testo=message.text
testo=testo.replace("preview->","")
message.reply(testo)
#get info from an ID
@bot.command("infoid", hidden=True)
def infobyid(chat, message, args):
if message.sender.id==owner:
if len(args)==1:
us=args[0]
try:
trid=bot.api.call("getChat", {"chat_id":us})
dizionario=(trid["result"])
messaggio=""
dizionario_lista=list(dizionario.keys())
for i in dizionario_lista:
if i == "username":
dizionario[i]="@"+dizionario[i]
messaggio+= (str(i)+": "+str(dizionario[i])+"\n")
message.reply(messaggio, syntax="plain")
except botogram.ChatUnavailableError as e:
message.reply(e.reason)
except (botogram.APIError) as e:
message.reply(e.description)
#this command should be run the first time you run the bot.
#in this way the DB won't be empty but it will add suddenly the right positions of the moment.
def first_time_in(store, posizione):
c.execute("INSERT INTO %s(posizione) VALUES(?)" % (store,),(posizione,))
conn.commit()
#only in case of new/empty db such as for the first time.
@bot.command("firstime", hidden=True)
def first_time(chat, message, args):
if message.sender.id==owner:
if (playstore_parse()) is not False:
first_time_in("playstore", playstore_parse())
message.reply("ok. Playstore is fine. You can start using the bot")
else:
message.reply("Playstore: an error occurred. please check the parse function.")
if (appstore_parse()) is not False:
first_time_in("appstore", appstore_parse())
message.reply("ok. Appstore is fine. You can start using the bot")
else:
message.reply("Appstore: an error occurred. please check the parse function.")
bot.process_backlog=True
if __name__ == "__main__":
bot.run()