-
Notifications
You must be signed in to change notification settings - Fork 0
/
TeleGenieBot.py
101 lines (79 loc) · 2.65 KB
/
TeleGenieBot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""
@Author: TUSHAR SINGH
@Topic: ChatBot // TeleGenie
@GitHub: https://github.com/SINGHxTUSHAR/TeleGenie
@reference: OpenAI , Aiogram, BotFather
"""
import logging
from aiogram import Bot, Dispatcher, executor, types
from dotenv import load_dotenv
import os
import openai
import sys
class Reference:
'''
A class to store previously response from the chatGPT API
'''
def __init__(self) -> None:
self.response = ""
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
reference = Reference()
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
#model name
MODEL_NAME = "gpt-3.5-turbo"
# Initialize bot and dispatcher
bot = Bot(token=TOKEN)
dispatcher = Dispatcher(bot)
def clear_past():
"""A function to clear the previous conversation and context.
"""
reference.response = ""
def clear_past():
"""A function to clear the previous conversation and context.
"""
reference.response = ""
@dispatcher.message_handler(commands=['start'])
async def welcome(message: types.Message):
"""
This handler receives messages with `/start` or `/help `command
"""
await message.reply("Hi\nI am Tele Bot!\Created by SINGHxTUSHAR. How can i assist you?")
@dispatcher.message_handler(commands=['clear'])
async def clear(message: types.Message):
"""
A handler to clear the previous conversation and context.
"""
clear_past()
await message.reply("I've cleared the past conversation and context.")
@dispatcher.message_handler(commands=['help'])
async def helper(message: types.Message):
"""
A handler to display the help menu.
"""
help_command = """
Hi There, I'm chatGPT Telegram bot created by SINGHxTUSHAR! Please follow these commands -
/start - to start the conversation
/clear - to clear the past conversation and context.
/help - to get this help menu.
I hope this helps. :)
"""
await message.reply(help_command)
@dispatcher.message_handler()
async def chatgpt(message: types.Message):
"""
A handler to process the user's input and generate a response using the chatGPT API.
"""
print(f">>> USER: \n\t{message.text}")
response = openai.ChatCompletion.create(
model = MODEL_NAME,
messages = [
{"role": "assistant", "content": reference.response}, # role assistant
{"role": "user", "content": message.text} #our query
]
)
reference.response = response.choices[0]['message']['content']
print(f">>> chatGPT: \n\t{reference.response}")
await bot.send_message(chat_id = message.chat.id, text = reference.response)
if __name__ == "__main__":
executor.start_polling(dispatcher, skip_updates=False)