使用 Telegram Bot 做客服系统来快速服务客户

用Telegram Bot做客服服务是一个常用且理想的方案,因为Bot不仅可以匹配问题关键字来回答,

还可以接入AI来自动回复客户问题,同时也可以接入在线客服,非常实时的响应客户问题,并且在

客服人员又有个很好的体验,不需要多端切换。实现方法也很简单,Bot在收到用户聊天内容时,将

这个内容直接转发给指定在线空闲的客服人员,或者直接转发到客服人员群组,客服在收到内容后可

直接回复,和正常聊天一样,回复内容会通过机器人转发给客户,这样就可以实现实时服务客户了。

实现

先去Telegram BotFather中创建一个Bot机器人,拿到机器人的token,用于后续服务启动机器人。

接收telegram bot消息,将私聊消息转发到指定的群,提供http接口发送私聊消息。

下载源代码:

1
git clone https://gitee.com/piao/telegram-bot-service.git

Bot运行有两种方式,如果有配置请求域名,则直接请求配置域名地址,/telegram路由可修改,

如果没有配置域名,则使用轮询方式poll_interval=1,推荐使用域名方式。

代码实现如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@asynccontextmanager
async def lifespan(app: FastAPI):
    if not Config.URL:
        updater = Updater(ptb.bot, update_queue=ptb.update_queue)
        await updater.initialize()
        await updater.start_polling(poll_interval=1)
    else:
        await ptb.bot.set_webhook(
            url=f'{Config.URL}/telegram',
            allowed_updates=Update.ALL_TYPES,
            drop_pending_updates=True,
        )

    async with ptb:
        await ptb.start()
        yield
        await ptb.stop()

install on linux

To install pip and the EB CLI

1
curl -O https://bootstrap.pypa.io/get-pip.py
1
python3 get-pip.py --user

Install Uvicorn

1
pip install uvicorn

Run the bot

Create venv

1
python -m venv .venv

手动运行服务器 - Uvicorn

1
2
3
4
5
6
7
source .venv/bin/activate

pip3 install -r requirements.txt

uvicorn app:app --host 0.0.0.0 --port 80 --env-file .env

deactivate

更多启动参数

1
uvicorn app:app --host 0.0.0.0 --port 8085 --log-level debug --access-log --workers 1 --no-server-header --date-header --env-file .env --lifespan on

参考