From 544595db2cb7db363f6f2c031c46e6733d7c7cf8 Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 17:17:52 +0800 Subject: [PATCH 1/7] telegram --- channel/channel_factory.py | 3 +++ channel/telegram/telegram_channel.py | 30 ++++++++++++++++++++++++++++ common/const.py | 1 + config-template.json | 6 +++--- 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 channel/telegram/telegram_channel.py 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..c989c2c --- /dev/null +++ b/channel/telegram/telegram_channel.py @@ -0,0 +1,30 @@ +import json +from concurrent.futures import ThreadPoolExecutor +import io +import requests +import telebot +from common.log import logger +from channel.channel import Channel +BOT_TOKEN = '5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg' +bot = telebot.TeleBot(BOT_TOKEN) +thread_pool = ThreadPoolExecutor(max_workers=8) + + +@bot.message_handler(commands=['ask']) +def send_welcome(msg): + TelegramChannel().handle(msg) + +class TelegramChannel(Channel): + def __init__(self): + pass + def startup(self): + logger.info("开始启动telegram机器人") + def handle(self, msg): + logger.debug("[Telegram]receive msg: " + msg.text) + thread_pool.submit(self._dosend,msg.text.replace("/ask",""),msg) + def _dosend(self,query,msg): + context= dict() + context['from_user_id'] = '1111' + reply_text = super().build_reply_content(query, context) + logger.info('[Telegram]] reply content: {}'.format(reply_text)) + bot.reply_to(msg,reply_text) \ 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..926784d 100644 --- a/config-template.json +++ b/config-template.json @@ -2,13 +2,13 @@ "model": { "type" : "openai", "openai": { - "api_key": "YOUR API KEY", - "conversation_max_tokens": 1000, + "api_key": "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", + "conversation_max_tokens": 2000, "character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。" } }, "channel": { - "type": "terminal", + "type": "telegram", "single_chat_prefix": ["bot", "@bot"], "single_chat_reply_prefix": "[bot] ", "group_chat_prefix": ["@bot"], From b82d578dfeacf94682857158823574309a5970bf Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 17:24:26 +0800 Subject: [PATCH 2/7] 111 --- channel/telegram/telegram_channel.py | 1 + config-template.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py index c989c2c..6d579a8 100644 --- a/channel/telegram/telegram_channel.py +++ b/channel/telegram/telegram_channel.py @@ -19,6 +19,7 @@ class TelegramChannel(Channel): pass def startup(self): logger.info("开始启动telegram机器人") + bot.infinity_polling() def handle(self, msg): logger.debug("[Telegram]receive msg: " + msg.text) thread_pool.submit(self._dosend,msg.text.replace("/ask",""),msg) diff --git a/config-template.json b/config-template.json index 926784d..0a3d14f 100644 --- a/config-template.json +++ b/config-template.json @@ -2,7 +2,7 @@ "model": { "type" : "openai", "openai": { - "api_key": "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", + "api_key": "1313212", "conversation_max_tokens": 2000, "character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。" } From 0af913cf823768ba3681544a0226e4c62360a3a9 Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 17:56:00 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- channel/telegram/telegram_channel.py | 49 ++++++++++++++++++++++++---- config-template.json | 3 ++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py index 6d579a8..3b8ced7 100644 --- a/channel/telegram/telegram_channel.py +++ b/channel/telegram/telegram_channel.py @@ -3,15 +3,17 @@ 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 -BOT_TOKEN = '5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg' -bot = telebot.TeleBot(BOT_TOKEN) +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=['ask']) +@bot.message_handler(content_types=['text']) def send_welcome(msg): + # telegram消息处理 TelegramChannel().handle(msg) class TelegramChannel(Channel): @@ -22,10 +24,45 @@ class TelegramChannel(Channel): bot.infinity_polling() def handle(self, msg): logger.debug("[Telegram]receive msg: " + msg.text) - thread_pool.submit(self._dosend,msg.text.replace("/ask",""),msg) + 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'] = '1111' + 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) \ No newline at end of file + 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.reply_to(msg, 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/config-template.json b/config-template.json index 0a3d14f..aec1cd3 100644 --- a/config-template.json +++ b/config-template.json @@ -30,6 +30,9 @@ "subject_keyword": ["bot", "@bot"], "host_email": "xxxx@gmail.com", "host_password": "GMAIL ACCESS KEY" + }, + "telegram":{ + "bot_token": "5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg" } } } From 52c0797230a294e6ff7815c71e00eec4d7032c92 Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 18:34:07 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E5=8F=91=E9=80=81=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- channel/telegram/telegram_channel.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py index 3b8ced7..9ae0c64 100644 --- a/channel/telegram/telegram_channel.py +++ b/channel/telegram/telegram_channel.py @@ -1,4 +1,4 @@ -import json +from telebot import util from concurrent.futures import ThreadPoolExecutor import io import requests @@ -10,6 +10,9 @@ 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, "

使用普通文本消息进行查询

‘画’开头使用绘画功能

", parse_mode = "HTML") @bot.message_handler(content_types=['text']) def send_welcome(msg): @@ -56,7 +59,9 @@ class TelegramChannel(Channel): # 图片发送 logger.info('[Telegrame] sendImage, receiver={}'.format(reply_user_id)) - bot.reply_to(msg, image_storage) + splitted_text = util.split_string(image_storage, 3000) + for text in splitted_text: + bot.send_message(msg.chat.id, text) except Exception as e: logger.exception(e) From ce8c46d32555d2b056e59b8304d9d3dd83cf47ce Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 18:37:24 +0800 Subject: [PATCH 5/7] 11 --- channel/telegram/telegram_channel.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py index 9ae0c64..7edfa3f 100644 --- a/channel/telegram/telegram_channel.py +++ b/channel/telegram/telegram_channel.py @@ -59,9 +59,10 @@ class TelegramChannel(Channel): # 图片发送 logger.info('[Telegrame] sendImage, receiver={}'.format(reply_user_id)) - splitted_text = util.split_string(image_storage, 3000) - for text in splitted_text: - bot.send_message(msg.chat.id, text) + # splitted_text = util.split_string(image_storage, 3000) + # for text in splitted_text: + # bot.send_message(msg.chat.id, text) + bot.reply_to(msg,pic_res) except Exception as e: logger.exception(e) From 98779fd6394e2f1ffe27e12637afd1498c579c49 Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 19:25:24 +0800 Subject: [PATCH 6/7] =?UTF-8?q?feat(*):=20telegram=20bot=E6=8E=A5=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- channel/telegram/telegram_channel.py | 12 +++++------- config-template.json | 6 +++--- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/channel/telegram/telegram_channel.py b/channel/telegram/telegram_channel.py index 7edfa3f..fc08d15 100644 --- a/channel/telegram/telegram_channel.py +++ b/channel/telegram/telegram_channel.py @@ -1,4 +1,3 @@ -from telebot import util from concurrent.futures import ThreadPoolExecutor import io import requests @@ -12,8 +11,9 @@ thread_pool = ThreadPoolExecutor(max_workers=8) @bot.message_handler(commands=['help']) def send_welcome(message): - bot.send_message(message.chat.id, "

使用普通文本消息进行查询

‘画’开头使用绘画功能

", parse_mode = "HTML") + bot.send_message(message.chat.id, "我是chatGPT机器人,开始和我聊天吧!", parse_mode = "HTML") +# 处理文本类型消息 @bot.message_handler(content_types=['text']) def send_welcome(msg): # telegram消息处理 @@ -23,11 +23,12 @@ class TelegramChannel(Channel): def __init__(self): pass def startup(self): - logger.info("开始启动telegram机器人") + 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: @@ -59,10 +60,7 @@ class TelegramChannel(Channel): # 图片发送 logger.info('[Telegrame] sendImage, receiver={}'.format(reply_user_id)) - # splitted_text = util.split_string(image_storage, 3000) - # for text in splitted_text: - # bot.send_message(msg.chat.id, text) - bot.reply_to(msg,pic_res) + bot.send_photo(msg.chat.id,image_storage) except Exception as e: logger.exception(e) diff --git a/config-template.json b/config-template.json index aec1cd3..4a527c6 100644 --- a/config-template.json +++ b/config-template.json @@ -2,8 +2,8 @@ "model": { "type" : "openai", "openai": { - "api_key": "1313212", - "conversation_max_tokens": 2000, + "api_key": "YOUR API KEY", + "conversation_max_tokens": 1000, "character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。" } }, @@ -32,7 +32,7 @@ "host_password": "GMAIL ACCESS KEY" }, "telegram":{ - "bot_token": "5684663516:AAFRYGIcDalEZzExyoBwt-t33BZjxcTISxg" + "bot_token": "xx:xx" } } } From 00d3946d3e627f26d0d87008ef0ccb7b13e73f6f Mon Sep 17 00:00:00 2001 From: luotuan Date: Sun, 26 Feb 2023 19:45:00 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=E6=9B=B4=E6=96=B0Readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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