添加对视频的支持

This commit is contained in:
2021-12-04 14:22:55 +08:00
parent 1f64ef27cb
commit e55b8f049b
5 changed files with 68 additions and 28 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
/credentials.py /credentials.py
/tmp_img /tmp_img
/.idea /.idea
/__pycache /__pycache
/tmp_video
+7 -4
View File
@@ -24,10 +24,13 @@ TEXT
``` ```
`WorkingDirectory`修改为程序所在目录, `WorkingDirectory`修改为程序所在目录,
在通过进程守护运行前请手动运行一次,设置配置文件! 在通过进程守护运行前请手动运行一次,设置配置文件!
通过 systemctl start fediversebridge 启动 通过 `systemctl start fediversebridge` 启动
systemctl enable fediversebridge 设置开机自起
关闭 systemctl stop fediversebridge `systemctl enable fediversebridge` 设置开机自起
禁用开机自起: systemctl disable fediversebridge
关闭 `systemctl stop fediversebridge`
禁用开机自起: `systemctl disable fediversebridge`
原README.md 原README.md
<details> <details>
Binary file not shown.
+59 -23
View File
@@ -1,5 +1,5 @@
#!/bin/env python #!/bin/env python
''' """
|--------------------------------------------------------------| |--------------------------------------------------------------|
| Telegram to Mastodon bridge | | Telegram to Mastodon bridge |
|--------------------------------------------------------------| |--------------------------------------------------------------|
@@ -9,7 +9,7 @@ Telegram bot API documentation:
Mastodon bot API documentation: Mastodon bot API documentation:
https://mastodonpy.readthedocs.io/en/stable/ https://mastodonpy.readthedocs.io/en/stable/
''' """
import os import os
import logging import logging
import time import time
@@ -18,9 +18,6 @@ from mastodon import Mastodon
import requests import requests
import json import json
''' '''
Basic setup Basic setup
''' '''
@@ -32,14 +29,18 @@ logger = telebot.logger.setLevel(logging.INFO)
if not os.path.isfile("credentials.py"): if not os.path.isfile("credentials.py"):
logging.info("No credentials found") logging.info("No credentials found")
telegram_token = input("输入你的telegram bot token: ") telegram_token = input("输入你的telegram bot token: ")
web_type=input("输入网站类型(misskey):") web_type = input("输入网站类型(misskey):")
if web_type == 'misskey': if web_type == 'misskey':
misskey_token = input("请输入Misskey bot token:") misskey_token = input("请输入Misskey bot token:")
misskey_instance = input("请输入Misskey实例地址:") misskey_instance = input("请输入Misskey实例地址(https://m.moec.top):")
misskey_visibility = input("帖子类型(public,home,followers)") misskey_visibility = input("帖子类型(public,home,followers)")
character_limit = input("字数限制:") character_limit = input("字数限制:")
with open("credentials.py", "w") as creds: with open("credentials.py", "w") as creds:
creds.write(f"telegram_token = '{telegram_token}'\nmisskey_token = '{misskey_token}'\nweb_type= '{web_type}'\nmisskey_instance = '{misskey_instance}'\nmisskey_visibility='{misskey_visibility}'\ncharacter_limit={character_limit}") creds.write(
f"telegram_token = '{telegram_token}'\nmisskey_token = '{misskey_token}'\nweb_type= '{web_type}'\n"
f"misskey_instance = '{misskey_instance}'\nmisskey_visibility='{misskey_visibility}'\n"
f"character_limit={character_limit}")
elif web_type == "mastodon": elif web_type == "mastodon":
character_limit = 500 character_limit = 500
mastodon_token = input("输入你的mastodon bot token: ") mastodon_token = input("输入你的mastodon bot token: ")
@@ -49,17 +50,20 @@ if not os.path.isfile("credentials.py"):
mastodon_visibility = input( mastodon_visibility = input(
"输入mastodon嘟文类型(public, unlisted, or private): ") "输入mastodon嘟文类型(public, unlisted, or private): ")
with open("credentials.py", "w") as creds: with open("credentials.py", "w") as creds:
creds.write(f"telegram_token = '{telegram_token}'\nweb_type= '{web_type}'\nmastodon_token = '{mastodon_token}'\nmastodon_instance = '{mastodon_instance}'\nmastodon_visibility={mastodon_visibility}") creds.write(
f"telegram_token = '{telegram_token}'\nweb_type= '{web_type}'\nmastodon_token = '{mastodon_token}'\n"
f"mastodon_instance = '{mastodon_instance}'\nmastodon_visibility={mastodon_visibility}")
else: else:
print("输入有误") print("输入有误")
else: else:
try: try:
from credentials import * from credentials import *
logging.info("Running normally")
logging.info("正常运行!")
except ImportError: except ImportError:
logging.fatal( logging.fatal(
"Something is wrong with credentials, delete credentials.py and try again") "credentials配置文件出错,请删除重试")
exit(1) exit(1)
''' '''
@@ -68,7 +72,7 @@ Bots
# Mastodon # Mastodon
if web_type == "mastodon": if web_type == "mastodon":
mastodon_bot = Mastodon(access_token=mastodon_token, mastodon_bot = Mastodon(access_token=mastodon_token,
api_base_url=mastodon_instance) # i.e.https://mastodon.social api_base_url=mastodon_instance) # i.e.https://mastodon.social
# Telegram # Telegram
# parse mode can be either HTML or MARKDOWN # parse mode can be either HTML or MARKDOWN
@@ -89,28 +93,24 @@ def ping_bots():
if a.status_code != 200: if a.status_code != 200:
logging.info(f"无法连接至TG API服务器") logging.info(f"无法连接至TG API服务器")
ping_telegram = bot.get_me() ping_telegram = bot.get_me()
logging.info(f"Running telegram as {ping_telegram.username}") logging.info(f"成功登入Telegram 机器人帐号 {ping_telegram.username}")
except: except:
logging.fatal("Failed to verify telegram token.") logging.fatal('无法验证 telegram token.')
exit(1) exit(1)
''' '''
Functions Functions
''' '''
def ping_web():
webget = requests.get(web)
if webget.status_code != 200:
print("实例连接错误")
exit(1)
def footer_text(message): def footer_text(message):
if message.forward_from_chat != None and message.chat.username != None: if message.forward_from_chat != None and message.chat.username != None:
final_text = message.text + "\r\rFrom " + message.chat.username + \ final_text = message.text + "\r\rFrom " + message.chat.username + \
f"\nForwarded from {message.forward_from_chat.title}" f"\nForwarded from {message.forward_from_chat.title}"
elif message.forward_from_chat != None and message.chat.username == None: elif message.forward_from_chat != None and message.chat.username == None:
final_text = message.text + "\r\r" + message.chat.title + \ final_text = message.text + "\r\r" + message.chat.title + \
f"\nForwarded from {message.forward_from_chat.title}" f"\nForwarded from {message.forward_from_chat.title}"
elif message.chat.username != None: elif message.chat.username != None:
final_text = message.text + "\r\rFrom " + message.chat.username final_text = message.text + "\r\rFrom " + message.chat.username
elif message.chat.username == None: elif message.chat.username == None:
@@ -227,14 +227,16 @@ def get_text(message):
''' '''
#Misskey # Misskey
@bot.channel_post_handler(content_types=["text"]) @bot.channel_post_handler(content_types=["text"])
def get_text(message): def get_text(message):
logging.info(f"New {message.content_type}") logging.info(f"New {message.content_type}")
status_text = footer_text(message) status_text = footer_text(message)
rjson = {'text': status_text, "localOnly": False, "visibility": misskey_visibility, "viaMobile": False, "i": misskey_token} rjson = {'text': status_text, "localOnly": False, "visibility": misskey_visibility, "viaMobile": False,
"i": misskey_token}
notepost = requests.post(misskey_instance + "/api/notes/create", json=rjson) notepost = requests.post(misskey_instance + "/api/notes/create", json=rjson)
logging.info(f"发布帖子成功")
@bot.channel_post_handler(content_types=["photo"]) @bot.channel_post_handler(content_types=["photo"])
def get_image(message): def get_image(message):
@@ -254,7 +256,41 @@ def get_image(message):
media_id_list=[] media_id_list=[]
media_id_list.append(json.loads(mediapost.text)["id"]) media_id_list.append(json.loads(mediapost.text)["id"])
rjson = {'text': caption, "localOnly": False, "visibility": misskey_visibility, "fileIds":media_id_list, "viaMobile": False, "i": misskey_token} rjson = {'text': caption, "localOnly": False, "visibility": misskey_visibility, "fileIds":media_id_list, "viaMobile": False, "i": misskey_token}
logging.info(f"上传图片成功")
posted = requests.post(misskey_instance + "/api/notes/create", json=rjson) posted = requests.post(misskey_instance + "/api/notes/create", json=rjson)
logging.info(f"发布帖子成功")
@bot.channel_post_handler(content_types=["video"])
def get_video(message):
logging.info(f"New {message.content_type}")
caption = footer_image(message)
fileID = message.video.file_id
logging.info(f"Video ID {fileID}")
file_info = bot.get_file(fileID)
downloaded_file = bot.download_file(file_info.file_path)
with open("tmp_video", "wb") as tmp_video:
tmp_video.write(downloaded_file)
if web_type == "misskey":
rmediajson = {"i": misskey_token}
files = {'file': ("tmp_video", open("tmp_video", "rb"))}
mediapost = requests.post(misskey_instance + '/api/drive/files/create', data=rmediajson, files=files)
media_id_list = []
media_id_list.append(json.loads(mediapost.text)["id"])
rjson = {'text': caption, "localOnly": False, "visibility": misskey_visibility,
"fileIds": media_id_list, "viaMobile": False, "i": misskey_token}
logging.info(f"上传视频成功")
posted = requests.post(misskey_instance + "/api/notes/create", json=rjson)
logging.info(f"发布帖子成功")
elif web_type == "mastodon":
media_id = mastodon_bot.media_post(
"tmp_video", mime_type=message.video.mime_type)
posted = mastodon_bot.status_post(
status=caption, media_ids=media_id, visibility=mastodon_visibility)
logging.info(f"Posted: {posted['uri']}")
''' '''
Finally run tg polling Finally run tg polling
Executable
BIN
View File
Binary file not shown.