import telebot
import openai
import os
telebot.apihelper.ENABLE_MIDDLEWARE = True
bot_token = os.getenv('5914803778:AAHdH3x4f9qCJuHv6d1HhW8MHydET0YiDqw')
openai.api_key = os.getenv('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')
bot = telebot.TeleBot(bot_token)
engine_map = {
"Davinci": "davinci",
"Curie": "curie",
"Babbage": "babbage",
"Ada": "ada",
"Cleverbot": "text-davinci-002"
}
@bot.middleware_handler(callback_query=bot.callback_query_handler(func=some_middleware))
def call_back_query(call):
if call.message:
if str(call.data) == 'stop':
bot.clear_step_handler_by_chat_id(chat_id=call.message.chat.id)
@bot.message_handler(commands=['start'])
def start_handler(message):
markup = telebot.types.InlineKeyboardMarkup()
eng_button_1 = telebot.types.InlineKeyboardButton(text='Davinci', callback_data=engine_map['Davinci'])
eng_button_2 = telebot.types.InlineKeyboardButton(text='Curie', callback_data=engine_map['Curie'])
eng_button_3 = telebot.types.InlineKeyboardButton(text='Babbage', callback_data=engine_map['Babbage'])
markup.row(eng_button_1, eng_button_2, eng_button_3)
bot.send_message(message.chat.id, 'Select chatGPT Engine:', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def callback_handler(callback_query):
message = callback_query.message
engine = callback_query.data
try:
text = 'Selected Engine is ' + list(engine_map.keys())[list(engine_map.values()).index(engine)]
bot.send_message(message.chat.id, text=text)
except KeyError:
bot.reply_to(message, "Error: Engine not found.")
user_data = {"engine": engine}
bot.register_next_step_handler(message, bot_answer, user_data)
def bot_answer(message, user_data):
try:
response = openai.Completion.create(
engine=user_data["engine"], prompt=message.text, max_tokens=100, n=1, stop=None, temperature=0.7)
bot.reply_to(message, response.choices[0].text)
except Exception as e:
bot.reply_to(message, "Error: " + str(e))
@bot.message_handler(commands=['stop'])
def stop_handler(message):
bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
markup = telebot.types.InlineKeyboardMarkup()
stop_button = telebot.types.InlineKeyboardButton(text='Stop')
markup.row(stop_button)
bot.send_message(message.chat.id, 'You have successfully stopped the bot!', reply_markup=markup)
@bot.message_handler(content_types=['text'])
def bot_answer(message):
if len(message.text) == 0:
return
markup = telebot.types.InlineKeyboardMarkup()
stop_button = telebot.types.InlineKeyboardButton(text='Stop', callback_data='stop')
markup.row(stop_button)
try:
engine = 'davinci'
if "engine" in user_data:
engine = user_data["engine"]
response = openai.Completion.create(
engine=engine, prompt=message.text, max_tokens=100, n=1, stop=None, temperature=0.7)
bot.reply_to(message, response.choices[0].text, reply_markup=markup)
except Exception as e:
bot.reply_to(message, "Error: " + str(e), reply_markup=markup)
bot.polling(none_stop=True)