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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
|
#!/usr/bin/env python
# pylint: disable=unused-argument, wrong-import-position
# This program is dedicated to the public domain under the CC0 license.
import logging
import io
import telegram.constants
from telegram import __version__ as TG_VER
from pprint import pprint
try:
from telegram import __version_info__
except ImportError:
__version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
if __version_info__ < (20, 0, 0, "alpha", 1):
raise RuntimeError(
f"This example is not compatible with your current PTB version {TG_VER}. To view the "
f"{TG_VER} version of this example, "
f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
)
from foursquare.poi import OSM_ENDPOINT
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes, MessageHandler, filters, \
ConversationHandler, CallbackContext
from config import BOT_TOKEN
from foursquare.poi import query_poi
from dbstore.dbm_store import get_loc
from toot import mastodon_client
from typing import TypedDict, List, cast
scheduler = None
PRIVACY, TOOT = map(chr, range(8, 10))
WAIT_LOC, LOCATION, LOCATION_SEARCH, PHOTO, PROCESS_PHOTO, COMMENT, SETTING = range(7)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
MAIN_MENU = ReplyKeyboardMarkup([
[KeyboardButton(text="Check-in here", request_location=True)],
# [KeyboardButton(text="/cancel")],
# [KeyboardButton(text="/setting")]
])
SKIP_LOCATION_SEARCH = "skip_location_search"
SKIP_MENU = InlineKeyboardMarkup([
[telegram.InlineKeyboardButton("Skip", callback_data=SKIP_LOCATION_SEARCH)]
])
# SETTING_MENU = InlineKeyboardMarkup(
# [
# [InlineKeyboardButton(text="/tos")],
# [InlineKeyboardButton(text="/back")],
# ]
# )
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
hello = "Hello, this is `checkin.bot`. \n\n" \
"This is a Telegram bot with functionality similar to Foursquare Swarm, " \
"but check in and post your location to the Fediverse (Mastodon/Pleroma) instead of Twitter.\n\n" \
"Aware of privacy concerns, this bot will not store your location data." \
"*Be safe and cautious when sharing your real time location on the web.* \n\n" \
"Start using this bot by sharing your location using Telegram context menu to it."
await update.message.reply_text(hello, parse_mode=telegram.constants.ParseMode.MARKDOWN)
await update.message.reply_text("Use bot keyboard to choose an action", reply_markup=MAIN_MENU)
return LOCATION
async def checkin(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
pprint(update.message.location)
if update.message.venue is not None:
fsq_id = update.message.venue.foursquare_id
title = update.message.venue.title
context.user_data["fsq_id"] = fsq_id
context.user_data["title"] = title
context.user_data["latitude"] = update.message.venue.location.latitude
context.user_data["longitude"] = update.message.venue.location.longitude
poi = get_loc(context.user_data["fsq_id"])
media_id = []
content = f"I'm at {poi['name']} in {poi['locality']}, {poi['region']}, {poi['osm_url']}"
status = mastodon_client.status_post(
content,
visibility="private",
media_ids=media_id)
context.user_data["status_id"] = status["id"]
context.user_data["status_content"] = content
print("status_id", context.user_data["status_id"])
await update.message.reply_text(
text=f"Selected place: {poi['name']}, \nPosted to Mastodon: {status['url']}",
parse_mode=telegram.constants.ParseMode.MARKDOWN,
)
prompt_attach_comment_msg = await update.message.reply_text(
"You can continue adding comments, or press skip to finish", reply_markup=SKIP_MENU)
context.user_data["prompt_attach_comment_msg_id"] = prompt_attach_comment_msg.message_id
return COMMENT
else:
context.user_data["latitude"] = update.message.location.latitude
context.user_data["longitude"] = update.message.location.longitude
await update.message.reply_text("Searching...", reply_markup=telegram.ReplyKeyboardRemove())
prompt_msg = await update.message.reply_text("You can input location search keywords or press skip",
reply_markup=SKIP_MENU)
context.user_data["prompt_msg_id"] = prompt_msg.message_id
return LOCATION_SEARCH
async def manual_location_process_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
# query = update.callback_query
# await query.answer()
# await query.delete_message()
loc = update.effective_message.text
osm_url = OSM_ENDPOINT.format(context.user_data["latitude"], context.user_data["longitude"])
media_id = []
content = f"I'm at {loc}, {osm_url}"
status = mastodon_client.status_post(
content,
visibility="private",
media_ids=media_id)
context.user_data["status_id"] = status["id"]
context.user_data["status_content"] = content
print("status_id", context.user_data["status_id"])
await update.message.reply_text(
text=f"Manually selected place: {loc}, \nPosted to Mastodon: {status['url']}",
parse_mode=telegram.constants.ParseMode.MARKDOWN,
# reply_markup=MAIN_MENU
)
prompt_attach_comment_msg = await update.message.reply_text(
"You can continue adding comments, or press skip to finish", reply_markup=SKIP_MENU)
context.user_data["prompt_attach_comment_msg_id"] = prompt_attach_comment_msg.message_id
return COMMENT
async def process_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
print("process_callback")
query = update.callback_query
await query.answer()
print(query.data)
context.user_data["fsq_id"] = query.data
await query.delete_message()
poi = get_loc(context.user_data["fsq_id"])
media_id = []
content = f"I'm at {poi['name']} in {poi['locality']}, {poi['region']}, {poi['osm_url']}"
status = mastodon_client.status_post(
content,
visibility="private",
media_ids=media_id)
context.user_data["status_id"] = status["id"]
context.user_data["status_content"] = content
print("status_id", context.user_data["status_id"])
await query.message.reply_text(
text=f"Selected place: {poi['name']}, `{query.data}`\nPosted to Mastodon: {status['url']}",
parse_mode=telegram.constants.ParseMode.MARKDOWN,
# reply_markup=MAIN_MENU
)
prompt_attach_comment_msg = await query.message.reply_text(
"You can continue adding comments, or press skip to finish", reply_markup=SKIP_MENU)
context.user_data["prompt_attach_comment_msg_id"] = prompt_attach_comment_msg.message_id
return COMMENT
async def location_search_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await context.bot.delete_message(update.effective_chat.id, context.user_data["prompt_msg_id"])
location_search = update.effective_message.text
latitude = context.user_data["latitude"]
longitude = context.user_data["longitude"]
keyboard = []
poi_result = query_poi(location_search, latitude, longitude)
if len(poi_result) == 0:
poi_result = query_poi("", latitude, longitude)
# for poi in poi_result:
# keyboard.append([
# InlineKeyboardButton(poi["name"], callback_data=poi["fsq_id"]),
# ])
if len(keyboard) == 0:
await update.message.reply_text("No nearby places found. You can input location name manually")
return WAIT_LOC
else:
reply_markup = InlineKeyboardMarkup(keyboard)
context.user_data["location_search"] = location_search
await update.message.reply_text("Where are you? ", reply_markup=reply_markup)
return WAIT_LOC
async def skip_location_search(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
print("skip: ", query.data)
await query.message.delete()
latitude = context.user_data["latitude"]
longitude = context.user_data["longitude"]
keyboard = []
for poi in query_poi("", latitude, longitude):
keyboard.append([
InlineKeyboardButton(poi["name"], callback_data=poi["fsq_id"]),
])
reply_markup = InlineKeyboardMarkup(keyboard)
await query.message.reply_text("Where are you? ", reply_markup=reply_markup)
return WAIT_LOC
async def comment_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await context.bot.delete_message(update.effective_chat.id, context.user_data["prompt_attach_comment_msg_id"])
comment = update.effective_message.text
mastodon_client.status_update(
status=f"{comment} " + context.user_data["status_content"],
id=context.user_data["status_id"])
context.user_data["status_content"] = f"{comment} " + context.user_data["status_content"]
prompt_attach_photo_msg = await update.message.reply_text(
"You can continue attaching photos, or press skip to finish", reply_markup=SKIP_MENU)
context.user_data["prompt_attach_photo_msg_id"] = prompt_attach_photo_msg.message_id
return PHOTO
async def skip_comment_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await context.bot.delete_message(update.effective_chat.id, context.user_data["prompt_attach_comment_msg_id"])
prompt_attach_photo_msg = await update.message.reply_text(
"You can continue attaching photos, or press skip to finish", reply_markup=SKIP_MENU)
context.user_data["prompt_attach_photo_msg_id"] = prompt_attach_photo_msg.message_id
return PHOTO
# async def tos(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# await update.message.reply_text("TOS", reply_markup=MAIN_MENU)
# async def setting(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# await update.message.reply_text("Setting", reply_markup=SETTING_MENU)
# return SETTING
# async def setting_process_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
# await update.message.reply_text("Setting Process Callback", reply_markup=SETTING_MENU)
# return ConversationHandler.END
# async def process_location(update: Update, context: ContextTypes.DEFAULT_TYPE):
# await update.message.reply_chat_action(telegram.constants.ChatAction.TYPING)
#
# fsq_id = context.user_data["fsq_id"]
# poi = get_loc(context.user_data["fsq_id"])
# media_id = []
#
# if context.user_data.get("photo") is not None:
# media = mastodon_client.media_post(context.user_data.get("photo"), mime_type="image/jpeg")
# media_id = [media["id"]]
# # else:
# # photo_url = get_poi_top_photo(context.user_data["fsq_id"])
# # if photo_url is not None:
# # with urllib.request.urlopen(photo_url) as response:
# # data = response.read()
# # media = mastodon_client.media_post(data, mime_type="image/jpeg")
# # media_id = [media["id"]]
#
# mastodon_client.status_post(
# f"I'm at {poi['name']} in {poi['locality']}, {poi['region']}, {poi['osm_url']}",
# visibility="private",
# media_ids=media_id)
#
# await update.message.delete()
# return ConversationHandler.END
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Displays info on how to use the bot."""
await update.message.reply_text("Use /start to test this bot.")
# async def setting_cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
# """Cancels and ends the conversation."""
# user = update.message.from_user
# logger.info("User %s canceled the conversation.", user.first_name)
# await update.message.reply_text(
# text="Setting canceled.",
# # "Bye! I hope we can talk again some day.",
# reply_markup=MAIN_MENU
# )
#
# return ConversationHandler.END
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Cancels and ends the conversation."""
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
await update.message.reply_text(
text="Canceled.",
# "Bye! I hope we can talk again some day.",
reply_markup=MAIN_MENU
)
return ConversationHandler.END
class MsgDict(TypedDict):
media_id: str
caption: str
status_id: int
content: str
chat_id: int
async def media_group_sender(context: CallbackContext):
context.job.data = cast(List[MsgDict], context.job.data)
media_id = []
chat_id = context.job.data[0].get("chat_id")
for msg_dict in context.job.data:
if len(media_id) >= 4:
print("Cannot attach more than 4 photos")
break
file = await context.bot.get_file(msg_dict.get("media_id"))
img = io.BytesIO()
await file.download_to_memory(img)
img.seek(0)
media = mastodon_client.media_post(img.read(), mime_type="image/jpeg")
media_id.append(media["id"])
mastodon_client.status_update(
status=msg_dict.get("content"),
id=msg_dict.get("status_id"),
media_ids=media_id)
await context.bot.send_message(chat_id=chat_id, text="Done",
reply_markup=MAIN_MENU
)
async def photo(update: Update, context: CallbackContext):
"""Stores the photo and asks for a location."""
await update.message.reply_chat_action(telegram.constants.ChatAction.TYPING)
try:
await context.bot.delete_message(chat_id=update.message.chat_id, message_id=context.user_data["prompt_attach_photo_msg_id"])
except telegram.error.BadRequest as e:
if "not found" in str(e.message):
print("prompt_attach_photo_msg already deleted")
pass
status_id = context.user_data["status_id"]
status_content = context.user_data["status_content"]
message = update.effective_message
context.user_data["media"] = []
if message.media_group_id:
media_id = message.photo[-1].file_id if message.photo else message.effective_attachment.file_id
msg_dict = {
"media_id": media_id,
"caption": message.caption_html,
"status_id": status_id,
"content": status_content,
"chat_id": message.chat_id,
}
jobs = context.job_queue.get_jobs_by_name(str(message.media_group_id))
if jobs:
jobs[0].data.append(msg_dict)
else:
context.job_queue.run_once(callback=media_group_sender, when=5, data=[msg_dict],
name=str(message.media_group_id))
else:
file = await update.message.effective_attachment[-1].get_file()
img = io.BytesIO()
await file.download_to_memory(img)
img.seek(0)
media = mastodon_client.media_post(img.read(), mime_type="image/jpeg")
mastodon_client.status_update(
status=status_content,
id=status_id,
media_ids=media["id"])
await update.message.reply_text(text="Done",
reply_markup=MAIN_MENU
)
async def skip_photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
await query.delete_message()
await query.message.reply_text(
text="Done.", reply_markup=MAIN_MENU
)
return ConversationHandler.END
def main() -> None:
application = Application.builder().token(BOT_TOKEN).build()
checkin_handler = ConversationHandler(
entry_points=[
CommandHandler("start", start),
MessageHandler(filters.LOCATION, checkin),
],
states={
LOCATION: [
MessageHandler(filters.LOCATION, checkin),
],
LOCATION_SEARCH: [
MessageHandler(filters.TEXT, location_search_callback),
CallbackQueryHandler(skip_location_search),
],
WAIT_LOC: [
CallbackQueryHandler(process_callback),
MessageHandler(filters.TEXT, manual_location_process_callback)
],
COMMENT: [
MessageHandler(filters.TEXT, comment_callback),
CallbackQueryHandler(skip_comment_callback),
],
PHOTO: [MessageHandler(filters.PHOTO, photo),
CallbackQueryHandler(skip_photo)],
},
fallbacks=[CommandHandler("cancel", cancel)],
per_message=False,
allow_reentry=True,
)
application.add_handler(checkin_handler, 1)
# Run the bot until the user presses Ctrl-C
application.run_polling()
if __name__ == "__main__":
main()
|