cleanup...

Signed-off-by: Alex A. Naanou <alex.nanou@gmail.com>
This commit is contained in:
Alex A. Naanou 2023-11-15 03:19:29 +03:00
parent 6d6118c68a
commit a4ed8ed948

240
bot.py
View File

@ -1,9 +1,14 @@
#!/usr/bin/python3 #!/usr/bin/python3
#----------------------------------------------------------------------
# systemd service... # systemd service...
#
# see: # see:
# https://tecadmin.net/run-shell-script-as-systemd-service/ # https://tecadmin.net/run-shell-script-as-systemd-service/
# https://tecadmin.net/setup-autorun-python-script-using-systemd/ # https://tecadmin.net/setup-autorun-python-script-using-systemd/
#
#
#----------------------------------------------------------------------
import telebot import telebot
import vk_api import vk_api
@ -13,153 +18,172 @@ import io
import datetime import datetime
import re import re
BASE_PATH = os.path.dirname(
os.path.abspath(__file__))
# Токен бота в Телеграме #----------------------------------------------------------------------
telegram_token = open(os.path.join(BASE_PATH, 'telegram.token'), 'r').read().strip() # Helpers...
# Токен группы ВКонтакте # XXX HACK -- mini/cute html2 -> markdown parser...
vk_token = open(os.path.join(BASE_PATH,'vk.token'), 'r').read().strip() def html2md(text):
text = re.sub(r'<b>(.*)</b>', r'*\1*', text, flags=re.I|re.M)
# ID группы ВКонтакте text = re.sub(r'<i>(.*)</i>', r'_\1_', text, flags=re.I|re.M)
vk_group_id = open(os.path.join(BASE_PATH,'vk_group.id'), 'r').read().strip() text = re.sub(r'<a\s+[ˆ>]*href="(.*)"[ˆ>]*>(.*)</a>', r'[\2](\1)', text, flags=re.I|re.M)
return text
def load(name):
return open(os.path.join(BASE_PATH, name), 'r').read().strip()
def getDate(): def getDate():
return datetime.datetime.now().strftime('%Y%m%d %H:%M:%S') return datetime.datetime.now().strftime('%Y%m%d %H:%M:%S')
#----------------------------------------------------------------------
BASE_PATH = os.path.dirname(
os.path.abspath(__file__))
telegram_token = load('telegram.token')
vk_token = load('vk.token')
vk_group_id = load('vk_group.id')
TEXT_SNIP = 50 TEXT_SNIP = 50
# CONTENT_TYPES = [
# "text", # Content types supported:
# "audio", # "text",
# "document", # "audio",
# "photo", # "document",
# "sticker", # "photo",
# "video", # "sticker",
# "video_note", # "video",
# "voice", # "video_note",
# "location", # "voice",
# "contact", # "location",
# "new_chat_members", # "contact",
# "left_chat_member", # "new_chat_members",
# "new_chat_title", # "left_chat_member",
# "new_chat_photo", # "new_chat_title",
# "delete_chat_photo", # "new_chat_photo",
# "group_chat_created", # "delete_chat_photo",
# "supergroup_chat_created", # "group_chat_created",
# "channel_chat_created", # "supergroup_chat_created",
# "migrate_to_chat_id", # "channel_chat_created",
# "migrate_from_chat_id", # "migrate_to_chat_id",
# "pinned_message", # "migrate_from_chat_id",
# ] # "pinned_message",
TRACK_TYPES = [ TRACK_TYPES = [
"text", "text",
"photo", "photo",
] ]
# Создаем объекты бота в Телеграме и API ВКонтакте
bot = telebot.TeleBot(telegram_token) bot = telebot.TeleBot(telegram_token)
vk_session = vk_api.VkApi(token=vk_token) vk_session = vk_api.VkApi(token=vk_token)
vk = vk_session.get_api() vk = vk_session.get_api()
print(f'{getDate()}: Bot started...')
#----------------------------------------------------------------------
# Text post handler...
#
# XXX TODO: # XXX TODO:
# - for some reason this does not see attached images at all... # - for some reason this does not see attached images at all...
# message.photo == None... # message.photo == None...
# - get telegram formatting (markdown???) # - get telegram formatting (markdown???)
# (see notes for: repost_photo_to_vk(..) below) # (see notes for: repost_photo_to_vk(..) below)
@bot.channel_post_handler(content_types=['text']) @bot.channel_post_handler(content_types=['text'])
def repost_text_to_vk(message): def repost_text_to_vk(message):
print(f"{getDate()}: Received message: {(message.text or '')[:TEXT_SNIP]}") print(f"{getDate()}: Received message: {(message.text or '')[:TEXT_SNIP]}")
attachments = [] attachments = []
# Если в сообщении есть изображения, загружаем их в ВКонтакте # XXX for some reason we are not getting any photos here...
# XXX for some reason we are not getting any photos here... print(f" --- PHOTOS: {message.photo}")
print(f" --- PHOTOS: {message.photo}") if message.photo:
if message.photo: for photo in message.photo:
for photo in message.photo: # Скачиваем фото
# Скачиваем фото file_info = bot.get_file(photo.file_id)
file_info = bot.get_file(photo.file_id) photo_url = "https://api.telegram.org/file/bot{}/{}".format(
photo_url = "https://api.telegram.org/file/bot{}/{}".format( telegram_token, file_info.file_path)
telegram_token, file_info.file_path)
# Загружаем фото в ВКонтакте # Загружаем фото в ВКонтакте
photo_id = upload_photo_to_vk(vk, photo_url) photo_id = upload_photo_to_vk(vk, photo_url)
attachments.append(photo_id) attachments.append(photo_id)
print(f" --- PHOTO {len(attachments)}: {attachments[-1]}") print(f" --- PHOTO {len(attachments)}: {attachments[-1]}")
# Публикуем сообщение в группе ВКонтакте # Публикуем сообщение в группе ВКонтакте
vk.wall.post( vk.wall.post(
owner_id="-" + vk_group_id, owner_id="-" + vk_group_id,
message=message.text, message=message.text,
attachments=",".join(attachments), attachments=",".join(attachments),
) )
print(f"{getDate()}: Posted message: {(message.text or '')[:TEXT_SNIP]}") print(f"{getDate()}: Posted message: {(message.text or '')[:TEXT_SNIP]}")
# XXX HACK -- mini/cute html2 -> markdown parser...
def html2md(text):
text = re.sub(r'<b>(.*)</b>', r'*\1*', text, flags=re.I|re.M)
text = re.sub(r'<i>(.*)</i>', r'_\1_', text, flags=re.I|re.M)
text = re.sub(r'<a\s+[ˆ>]*href="(.*)"[ˆ>]*>(.*)</a>', r'[\2](\1)', text, flags=re.I|re.M)
return text
#----------------------------------------------------------------------
# Image post handler...
#
# see: # see:
# https://github.com/python273/vk_api/blob/master/examples/upload_photo.py # https://github.com/python273/vk_api/blob/master/examples/upload_photo.py
# https://vk-api.readthedocs.io/en/latest/upload.html (see: photo_wall(..)) # https://vk-api.readthedocs.io/en/latest/upload.html (see: photo_wall(..))
# #
# XXX TODO # XXX TODO
# - multiple images per post are treated as separate posts for some reason -- need # - multiple images per post are treated as separate posts for some reason -- need
# to find a way to group... # to find a way to group...
# - get telegram formatting: # - get telegram formatting:
# - links # - links
# - header # - header
# - ... # - ...
# - Q: is the largest image alwways the last?? # - Q: is the largest image alwways the last??
# ...check telegram API # ...check telegram API
@bot.channel_post_handler(content_types=['photo']) @bot.channel_post_handler(content_types=['photo'])
def repost_photo_to_vk(message): def repost_photo_to_vk(message):
print(f"{getDate()}: Received photo: {(message.caption or '')[:TEXT_SNIP]}") print(f"{getDate()}: Received photo: {(message.caption or '')[:TEXT_SNIP]}")
# download images (memory)... # download images (memory)...
upload = vk_api.VkUpload(vk_session) upload = vk_api.VkUpload(vk_session)
ids = [] ids = []
photo = message.photo[-1] photo = message.photo[-1]
file_info = bot.get_file(photo.file_id) file_info = bot.get_file(photo.file_id)
photo_url = "https://api.telegram.org/file/bot{}/{}".format( photo_url = "https://api.telegram.org/file/bot{}/{}".format(
telegram_token, telegram_token,
file_info.file_path) file_info.file_path)
response = requests.get(photo_url) response = requests.get(photo_url)
# upload images... # upload images...
photo_info = upload.photo_wall( photo_info = upload.photo_wall(
io.BytesIO(response.content), io.BytesIO(response.content),
group_id=vk_group_id)[0] group_id=vk_group_id)[0]
ids += [ ids += [
"photo{}_{}".format( "photo{}_{}".format(
photo_info["owner_id"], photo_info["owner_id"],
photo_info["id"]) ] photo_info["id"]) ]
print(f" --- PHOTO {len(ids)}: {ids[-1]}") print(f" --- PHOTO {len(ids)}: {ids[-1]}")
vk.wall.post( vk.wall.post(
owner_id="-" + vk_group_id, owner_id="-" + vk_group_id,
message=message.caption, message=message.caption,
#message=message.html_caption, #message=message.html_caption,
attachments=",".join(ids)) attachments=",".join(ids))
print(f"{getDate()}: Posted photo: {(message.caption or '')[:TEXT_SNIP]}") print(f"{getDate()}: Posted photo: {(message.caption or '')[:TEXT_SNIP]}")
# Запускаем бота в Телеграме с измененными параметрами опроса
#----------------------------------------------------------------------
# Start...
print(f'{getDate()}: Bot started...')
bot.polling(none_stop=False, interval=0, timeout=60) bot.polling(none_stop=False, interval=0, timeout=60)
#----------------------------------------------------------------------
# vim:set ts=4 sw=4 :