-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProduct_Hunt_bot.py
370 lines (253 loc) · 12.7 KB
/
Product_Hunt_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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import telebot
import gspread
import requests
import threading
import time
import schedule
import datetime
from telebot.types import KeyboardButton, ReplyKeyboardMarkup
from telebot import custom_filters
from oauth2client.service_account import ServiceAccountCredentials
dotenv.load_dotenv()
# your Token from @Botfather
API_KEY = os.getenv("API_KEY")
my_id = os.getenv("my_id") # your personal chat ID
analyst_id = os.getenv("analyst_id") # your analyst chat ID
ph_auth = os.getenv("ph_auth") # your token for accessing the Product Hunt API
# the place where your creds.json from Google is stored
creds_location = os.getenv("creds_location")
forms_url = os.getenv("forms_url") # your URL to the Google Forms for feedback
# your URL to the Google Spreadsheet for analytics
spreadsheet_url = os.getenv("spreadsheet_url")
pod_img = "AgACAgUAAxkBAAMsYUtpwf4IweE0MYMGR9Vbpe1xOiEAAuStMRu77WBWjmCIZUpTv9oBAAMCAAN5AAMhBA"
pom_img = "AgACAgUAAxkBAAIB9WFO1TnJhBFbYkS0O-VdaYA9UA3SAAJkrDEbzKd4Vq56YH6fcfZFAQADAgADeQADIQQ"
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name(creds_location, scope)
client = gspread.authorize(creds)
analytics_PRODUCT_HUNT_BOT = client.open(
"ANALYTICS").worksheet("PRODUCT-HUNT_BOT")
database = client.open("PRODUCT HUNT BOT DATABASE").worksheet("DATABASE")
bot = telebot.TeleBot(API_KEY)
@bot.message_handler(commands=['start'])
def start(message):
col = database.col_values(1)
if str(message.chat.id) not in col:
database.append_row([message.chat.id, 'daily/monthly'])
analytics_PRODUCT_HUNT_BOT.update_acell('F10', str(
len(database.col_values(1))-1).replace("'", " "))
msg = '''
Welcome to the [Product Hunt](https://www.producthunt.com/) Telegram bot\! 👶
I can send you daily or monthly updates regarding posts on [Product Hunt](https://www.producthunt.com/)\. An opt\-out is possible if you would like to trigger me manually\.
Send /help for more information\.
Enjoy\! 🎉
'''
bot.send_message(message.chat.id, msg,
parse_mode="MarkdownV2", disable_web_page_preview=True)
start_count = analytics_PRODUCT_HUNT_BOT.acell('F3').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F3', str(int(start_count)+1).replace("'", " "))
@bot.message_handler(commands=["daily"])
def pod(message):
url = "https://api.producthunt.com/v1/posts"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {ph_auth}",
"Host": "api.producthunt.com"
}
posts, MSG = requests.get(url=url, headers=headers).json()['posts'], ""
bot.send_photo(message.chat.id, pod_img)
for count, post in enumerate(posts):
if(count+1) == len(posts):
bot.send_message(message.chat.id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
elif (count + 1) % 10 == 0:
bot.send_message(message.chat.id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
MSG = ""
MSG += f'➤ <b><a href="{post["redirect_url"]}">{post["name"]}: </a></b>'
MSG += f'<a href="{post["discussion_url"]}">{post["tagline"]}</a>\n\n'
END = "<i>For more such amazing products, please visit our \
<b><a href='https://www.producthunt.com/'>website.</a></b></i>"
bot.send_message(message.chat.id, END, parse_mode="HTML",
disable_web_page_preview=True)
ph_count = analytics_PRODUCT_HUNT_BOT.acell('F4').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F4', str(int(ph_count)+1).replace("'", " "))
@bot.message_handler(commands=["monthly"])
def pom(message):
month = datetime.datetime.today().month # TODO: Fix for Jan 1, 2022
year = datetime.datetime.today().year
url = f"https://api.producthunt.com/v1/posts/all?sort_by=votes_count&order=desc&search[featured_month]={month}&search[featured_year]={year}"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {ph_auth}",
"Host": "api.producthunt.com"
}
posts, MSG = requests.get(url=url, headers=headers).json()['posts'], ""
bot.send_photo(message.chat.id, pom_img)
for count, post in enumerate(posts):
if(count+1) == len(posts):
bot.send_message(message.chat.id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
elif (count + 1) % 10 == 0:
bot.send_message(message.chat.id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
MSG = ""
MSG += f'➤ <b><a href="{post["redirect_url"]}">{post["name"]}: </a></b>'
MSG += f'<a href="{post["discussion_url"]}">{post["tagline"]}</a>\n\n'
END = "<i>For more such amazing products, please visit our \
<b><a href='https://www.producthunt.com/'>website.</a></b></i>"
bot.send_message(message.chat.id, END, parse_mode="HTML",
disable_web_page_preview=True)
ph_count = analytics_PRODUCT_HUNT_BOT.acell('F5').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F5', str(int(ph_count)+1).replace("'", " "))
@bot.message_handler(commands=["schedule"])
def sch(message):
mark_up = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
B1 = KeyboardButton(text='DAILY UPDATES')
B2 = KeyboardButton(text='MONTHLY UPDATES')
B3 = KeyboardButton(text='DAILY & MONTHLY')
B4 = KeyboardButton(text='MANUAL UPDATES')
mark_up.row(B1, B2)
mark_up.row(B3, B4)
bot.send_message(
message.chat.id, "How often would you like to recieve updates?", reply_markup=mark_up)
sch_count = analytics_PRODUCT_HUNT_BOT.acell('F6').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F6', str(int(sch_count)+1).replace("'", " "))
@bot.message_handler(text=['DAILY UPDATES'])
def text_filter(message):
cell = database.find(str(message.chat.id))
r, c = cell.row, cell.col+1
database.update_cell(r, c, 'daily')
bot.send_message(message.chat.id, "PREFERENCE: DAILY UPDATES")
@bot.message_handler(text=['MONTHLY UPDATES'])
def text_filter(message):
cell = database.find(str(message.chat.id))
r, c = cell.row, cell.col+1
database.update_cell(r, c, 'monthly')
bot.send_message(message.chat.id, "PREFERENCE: MONTHLY UPDATES")
@bot.message_handler(text=['DAILY & MONTHLY'])
def text_filter(message):
cell = database.find(str(message.chat.id))
r, c = cell.row, cell.col+1
database.update_cell(r, c, 'daily/monthly')
bot.send_message(message.chat.id, "PREFERENCE: DAILY & MONTHLY UPDATES")
@bot.message_handler(text=['MANUAL UPDATES'])
def text_filter(message):
cell = database.find(str(message.chat.id))
r, c = cell.row, cell.col+1
database.update_cell(r, c, 'none')
bot.send_message(message.chat.id, "PREFERENCE: MANUAL UPDATES")
@bot.message_handler(commands=['contact'])
def contact(message):
contact_info = '''
*CONTACT :*\n
Telegram: https://t\.me/Marvin\_Marvin\n
Mail: marvin@poopjournal\.rocks\n
Issue: https://github\.com/Crazy\-Marvin/ProductHuntTelegramBot/issues\n
Source: https://github\.com/Crazy\-Marvin/ProductHuntTelegramBot
'''
bot.send_message(message.chat.id, contact_info,
parse_mode='MarkdownV2', disable_web_page_preview=True)
contact_count = analytics_PRODUCT_HUNT_BOT.acell('F8').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F8', str(int(contact_count)+1).replace("'", " "))
@bot.message_handler(commands=['feedback'])
def feedback(message):
bot.send_message(message.chat.id, "Want to give us a feedback?\n\n\
{forms_url} \n\nPlease fill out this Google Form☝🏻", disable_web_page_preview=True)
feedback_count = analytics_PRODUCT_HUNT_BOT.acell('F7').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F7', str(int(feedback_count)+1).replace("'", " "))
@bot.message_handler(commands=['help'])
def help(message):
msg = '''
Thanks for using the Product Hunt Telegram bot.
After starting the bot with /start you will receive all Product Hunt posts daily. It is possible to opt-out or change the schedule with the /schedule command.
Sending /ph will send you all posts from today again.
If you would like to contact me send /contact.
Feedback is very appreaciated by filling out a Google form which the bot will send you after sending him /feedback.
Have fun! 🥳'''
bot.send_message(message.chat.id, msg)
help_count = analytics_PRODUCT_HUNT_BOT.acell('F9').value
analytics_PRODUCT_HUNT_BOT.update_acell(
'F9', str(int(help_count)+1).replace("'", " "))
@bot.message_handler(commands=['logs'])
def logs(message):
if message.chat.id == my_id or message.chat.id == analyst_id:
bot.send_message(message.chat.id, f"Check out the *[ANALYTICS]{spreadsheet_url})* for the month\.",
parse_mode="MarkdownV2", disable_web_page_preview=True)
bot.add_custom_filter(custom_filters.TextMatchFilter())
def monthly():
if datetime.date.today() != 1:
return
month = datetime.datetime.today().month - 1 # TODO: Fix for Jan 1, 2022
year = datetime.datetime.today().year
url = f"https://api.producthunt.com/v1/posts/all?sort_by=votes_count&order=desc&search[featured_month]={month}&search[featured_year]={year}"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {ph_auth}",
"Host": "api.producthunt.com"
}
posts, MSG = requests.get(url=url, headers=headers).json()['posts'], ""
users = database.get_all_records()
for user in users:
if user["Updates"] == "monthly" or user["Updates"] == "daily/monthly":
chat_id = user["Chat Id"]
bot.send_photo(chat_id, pom_img)
for count, post in enumerate(posts):
if(count+1) == len(posts):
bot.send_message(chat_id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
elif (count + 1) % 10 == 0:
bot.send_message(chat_id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
MSG = ""
MSG += f'➤ <b><a href="{post["redirect_url"]}">{post["name"]}: </a></b>'
MSG += f'<a href="{post["discussion_url"]}">{post["tagline"]}</a>\n\n'
END = "<i>For more such amazing products, please visit our <b><a href='https://www.producthunt.com/'>website.</a></b></i>"
bot.send_message(chat_id, END, parse_mode="HTML",
disable_web_page_preview=True)
def daily():
url = "https://api.producthunt.com/v1/posts/"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {ph_auth}",
"Host": "api.producthunt.com"
}
posts, MSG = requests.get(url=url, headers=headers).json()['posts'], ""
users = database.get_all_records()
for user in users:
if user["Updates"] == "daily" or user["Updates"] == "daily/monthly":
chat_id = user["Chat Id"]
bot.send_photo(chat_id, pod_img)
for count, post in enumerate(posts):
if(count+1) == len(posts):
bot.send_message(chat_id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
elif (count + 1) % 10 == 0:
bot.send_message(chat_id, MSG, parse_mode="HTML",
disable_web_page_preview=True, disable_notification=True)
MSG = ""
MSG += f'➤ <b><a href="{post["redirect_url"]}">{post["name"]}: </a></b>'
MSG += f'<a href="{post["discussion_url"]}">{post["tagline"]}</a>\n\n'
END = "<i>For more such amazing products, please visit our <b><a href='https://www.producthunt.com/'>website.</a></b></i>"
bot.send_message(chat_id, END, parse_mode="HTML",
disable_web_page_preview=True)
schedule.every().day.at("00:00").do(daily)
schedule.every().day.at("12:00").do(monthly)
# TODO: Create a separate script and host it as a main thread on server for better performance 🤔
def thrd():
while True:
schedule.run_pending()
time.sleep(5)
t = threading.Thread(target=thrd)
t.start()
bot.polling()