diff --git a/README.md b/README.md index 17daee0..9cd6be0 100644 --- a/README.md +++ b/README.md @@ -238,3 +238,19 @@ Follow [官方文档](https://support.google.com/mail/answer/185833?hl=en) to cr } } ``` +### 6. Telegram + +telegram 机器人申请可以自行谷歌下,很简单。重要的是获取机器人的token id。 + +**依赖安装** pip install pyTelegramBotAPI + +**配置** + +```json +"channel": { + "type": "telegram", + "telegram":{ + "bot_token": "你的bot token id" + } + } +``` \ No newline at end of file diff --git a/channel/channel_factory.py b/channel/channel_factory.py index 693aae1..d900276 100644 --- a/channel/channel_factory.py +++ b/channel/channel_factory.py @@ -28,6 +28,9 @@ def create_channel(channel_type): elif channel_type == const.GMAIL: from channel.gmail.gmail_channel import GmailChannel return GmailChannel() + elif channel_type == const.TELEGRAM: + from channel.telegram.telegram_channel import TelegramChannel + return TelegramChannel() else: raise RuntimeError diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py new file mode 100644 index 0000000..fc08d15 --- /dev/null +++ b/channel/telegram/telegram_channel.py @@ -0,0 +1,72 @@ +from concurrent.futures import ThreadPoolExecutor +import io +import requests +import telebot +from common import const +from common.log import logger +from channel.channel import Channel +from config import channel_conf_val, channel_conf +bot = telebot.TeleBot(token=channel_conf(const.TELEGRAM).get('bot_token')) +thread_pool = ThreadPoolExecutor(max_workers=8) + +@bot.message_handler(commands=['help']) +def send_welcome(message): + bot.send_message(message.chat.id, "我是chatGPT机器人,开始和我聊天吧!", parse_mode = "HTML") + +# 处理文本类型消息 +@bot.message_handler(content_types=['text']) +def send_welcome(msg): + # telegram消息处理 + TelegramChannel().handle(msg) + +class TelegramChannel(Channel): + def __init__(self): + pass + def startup(self): + logger.info("开始启动[telegram]机器人") + bot.infinity_polling() + def handle(self, msg): + logger.debug("[Telegram]receive msg: " + msg.text) + img_match_prefix = self.check_prefix(msg, channel_conf_val(const.TELEGRAM, 'image_create_prefix')) + # 如果是图片请求 + if img_match_prefix: + thread_pool.submit(self._do_send_img, msg, str(msg.chat.id)) + else: + thread_pool.submit(self._dosend,msg.text,msg) + + def _dosend(self,query,msg): + context= dict() + context['from_user_id'] = str(msg.chat.id) + reply_text = super().build_reply_content(query, context) + logger.info('[Telegram]] reply content: {}'.format(reply_text)) + bot.reply_to(msg,reply_text) + + def _do_send_img(self, msg, reply_user_id): + try: + if not msg: + return + context = dict() + context['type'] = 'IMAGE_CREATE' + img_url = super().build_reply_content(msg.text, context) + if not img_url: + return + + # 图片下载 + pic_res = requests.get(img_url, stream=True) + image_storage = io.BytesIO() + for block in pic_res.iter_content(1024): + image_storage.write(block) + image_storage.seek(0) + + # 图片发送 + logger.info('[Telegrame] sendImage, receiver={}'.format(reply_user_id)) + bot.send_photo(msg.chat.id,image_storage) + except Exception as e: + logger.exception(e) + + + def check_prefix(self,msg,prefix_list): + for prefix in prefix_list: + if msg.text.startswith(prefix): + return prefix + return None \ No newline at end of file diff --git a/common/const.py b/common/const.py index 17ecc4d..b403c28 100644 --- a/common/const.py +++ b/common/const.py @@ -4,6 +4,7 @@ WECHAT = "wechat" WECHAT_MP = "wechat_mp" WECHAT_MP_SERVICE = "wechat_mp_service" GMAIL = "gmail" +TELEGRAM = "telegram" # model OPEN_AI = "openai" diff --git a/config-template.json b/config-template.json index b601557..4a527c6 100644 --- a/config-template.json +++ b/config-template.json @@ -8,7 +8,7 @@ } }, "channel": { - "type": "terminal", + "type": "telegram", "single_chat_prefix": ["bot", "@bot"], "single_chat_reply_prefix": "[bot] ", "group_chat_prefix": ["@bot"], @@ -30,6 +30,9 @@ "subject_keyword": ["bot", "@bot"], "host_email": "xxxx@gmail.com", "host_password": "GMAIL ACCESS KEY" + }, + "telegram":{ + "bot_token": "xx:xx" } } }