搭建一个 Telegram 机器人来使用 ChatGPT

该机器人使用python 编写
需要安装的包:
openai==0.26.5
python-telegram-bot==20.1

代码如下:

# -*- coding: utf-8 -*-

import logging
import openai
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, CallbackContext, filters

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

openai.api_key = "sk-i5N***" # 填写 openai 的接口

bot_key = "571**:AA***" # 填写机器人 token


# ChatGPT初始化


def reply_text(list_msg,list_ans,message):
    send_msg=[{"role":"system","content": "Hello"}]
    try:
        for i in range(len(list_msg)):
            _msg={"role":"user","content": list_msg[i]}
            send_msg.append(_msg)
            _ans={"role":"assistant","content": list_ans[i]}
            send_msg.append(_ans)

        _msg={"role":"user","content": message}
        send_msg.append(_msg)
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=send_msg
        )
        return response["choices"][0]["message"]["content"]
    except Exception as error:
        print(str(error)[:100])

def create_img(question: str):
        try:
            response = openai.Image.create(
                prompt=question,
                n=1,
                size="1024x1024"
            )
            image_url = response['data'][0]['url']
            return image_url
        except Exception as error:
            print(str(error)[:101])


async def echo(update: Update, context: CallbackContext) -> None:
    """Echo the user message."""
    mychatids = {"550***" , "***"} # 填写需要使用的telegram id
    firstword = ["画","Draw","draw","plot","Plot"]
    if 'history_list_msg' not in locals():
        history_list_msg=[]
        history_list_ans=[]
    if str(update.effective_user.id) not in mychatids :
        return None
    elif (update.message.text.split()[0] not in firstword) and (update.message.text[0] not in firstword):
        result = reply_text(history_list_msg, history_list_ans, update.message.text)
    else:
        result = create_img(update.message.text)
    print(f"查询用户: {update.effective_user.full_name}|{update.effective_user.id},查询内容: {update.message.text},------- 返回内容: {result}")
    await update.message.reply_text(text=f"{result}")

    history_list_msg.append(update.message.text)
    if len(history_list_msg)>10:
        history_list_msg=history_list_msg[-10:]
    history_list_ans.append(result)
    if len(history_list_ans)>10:
        history_list_ans=history_list_ans[-10:]


if __name__ == '__main__':
    application = ApplicationBuilder().token(bot_key).build()
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
    application.run_polling()

后记:使用 model=”gpt-3.5-turbo” (Mar 5th)