-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtgbot.py
123 lines (95 loc) · 3.2 KB
/
tgbot.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
from flask import Flask, request
import telepot
from reddit import authenticate, get_posts
from dotenv import load_dotenv
from storit import Storit
MSG_DB = 'last'
SUBS_DB = 'subs'
load_dotenv()
def get_last_message(user_id):
store = Storit(MSG_DB)
return store[user_id]
def save_last_message(user_id, msg_id):
store = Storit(MSG_DB)
store[user_id] = msg_id
def subscribe_user(user_id):
store = Storit(SUBS_DB)
store[user_id] = True
logging.debug('user %s has subscribed' % user_id)
def unsubscribe_user(user_id):
store = Storit(SUBS_DB)
ret = store.delete_if_exists(user_id)
if ret:
logging.debug('user %s has unsubscribed' % user_id)
def get_subscribed_users():
store = Storit(SUBS_DB)
return store.keys()
def get_pending_messages(user_id, ads):
'''
Returns pending messages for each user
The order is from oldest to newest
'''
last_msg = get_last_message(user_id)
if last_msg and last_msg in ads:
pos = ads.index(last_msg)
if pos > 0:
# send pending ads
return reversed(ads[:pos])
else:
# no new ads
return []
# send all ads
return reversed(ads)
def send_ads_to_user(tgbot, user, manual=False):
posts = get_hiring_posts(reddit=authenticate())
pending = get_pending_messages(user, posts)
if pending:
lm = None
for post in pending:
lm = post
try:
tgbot.sendMessage(user, "*{}*\n[link]({})".format(post.title, post.url), parse_mode='Markdown')
except telepot.exception.BotWasBlockedError:
logging.debug('User {} blocked me'.format(user))
assert lm is not None
logging.debug("saving user %s with msg %s" % (user, lm))
save_last_message(user, lm)
elif manual:
tgbot.sendMessage(user, 'Nothing new to see here')
secret = os.getenv('botsecret')
bot = os.getenv('botid')
bot.setWebhook("https://mybot.mydomain.net/{}".format(secret),
max_connections=1)
app = Flask(__name__)
@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
update = request.get_json()
if "message" in update:
text = update["message"]["text"]
chat_id = update["message"]["chat"]["id"]
if text == '/new':
send_ads_to_user(tgbot=bot, user=chat_id, manual=True)
elif text == '/sub':
subscribe_user(chat_id)
bot.sendMessage(chat_id, 'New submissions will be notified'
' every 10 minutes (if any)')
elif text == '/unsub':
unsubscribe_user(chat_id)
bot.sendMessage(chat_id, 'Subscription cancelled')
else:
bot.sendMessage(chat_id, "Doesn't look like anything to me..")
return 'OK'
@app.route('/crony-secret-url')
def periodic_msg_pooler():
"""
Curl this URL every x minutes with cron.
(This is a quick hack for avoiding something like apscheduler)
"""
for user in get_subscribed_users():
logging.info('sending ads to user %s' % user)
send_ads_to_user(tgbot=bot, user=user)
return 'OK'