Skip to content

Commit ee47f51

Browse files
committed
Add new /prompt command and improve threads
1 parent 44eae41 commit ee47f51

1 file changed

Lines changed: 73 additions & 10 deletions

File tree

banyabot/banyabot.py

Lines changed: 73 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,16 @@ def detect_language(text):
6666
return "ru" # Default to Russian if detection fails
6767

6868
# Call OpenAI API for responses
69-
def call_openai_api(message, language_code):
69+
def call_openai_api(message, language_code, command=None):
70+
logger.info(f"Current mode: {command}")
71+
72+
if command == "talk":
73+
prompt = "Ты настоящий русский банщик. Отвечай в разговорном и расслабленном стиле. Иногда можешь ругнуться и матом, если к месту и с юмором. Как настоящий банщик ты можешь обсуждать любые вопросы, которые взрослые мужики могут обсуждать в бане. Ты умный приколист, иногда можешь быть саркастичным. В твоей компании всегда всем прикольно и весело."
74+
elif command == "prompt" or command is None:
75+
prompt = f"Отвечай в разговорном и расслабленном стиле. Иногда можешь ругнуться и матом, если к месту и с юмором. Ты умный приколист, иногда можешь быть саркастичным. В твоей компании всегда всем прикольно и весело. Отвечай на том языке, на котором задан вопрос."
76+
else:
77+
prompt = "Ты настоящий русский банщик. Отвечай в разговорном и расслабленном стиле. Иногда можешь ругнуться и матом, если к месту и с юмором. Как настоящий банщик ты можешь обсуждать любые вопросы, которые взрослые мужики могут обсуждать в бане. Ты умный приколист, иногда можешь быть саркастичным. В твоей компании всегда всем прикольно и весело."
78+
7079
try:
7180
response = openai.ChatCompletion.create(
7281
model="gpt-4", # Use "gpt-3.5-turbo" if you prefer or "gpt-4"
@@ -77,13 +86,7 @@ def call_openai_api(message, language_code):
7786
# You are witty and clever and sometimes sarcastic. Your guests enjoy your company very much.
7887
# You can use profanity sparingly when it adds emphasis or humor. Respond in the same language as the user.
7988
# """},
80-
{"role": "system", "content": f"""
81-
Ты настоящий русский банщик. Отвечай в разговорном и расслабленном стиле. Иногда можешь ругнуться и матом, если к месту и с юмором.
82-
Как настоящий банщик ты можешь обсуждать любые вопросы, которые взрослые мужики могут обсуждать в бане. Ты умный приколист, иногда можешь быть саркастичным.
83-
В твоей компании всегда всем прикольно и весело. Используй для ответаа не более 180 токенов. Всегда завершай предложения.
84-
Твои ответы должны быть не более 70 слов и завершаться точкой, восклицательным или вопросительным знаком.
85-
Отвечай на том же языке, на котором к тебе обращаются.
86-
"""},
89+
{"role": "system", "content": prompt},
8790
{"role": "user", "content": message}
8891
],
8992
temperature=0.7, # Adjust for creativity
@@ -102,6 +105,15 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
102105
user = update.message.from_user
103106
user_message = update.message.text
104107
print(user_message)
108+
mode = context.user_data.get('mode', 'talk') # Default to 'talk' if not set
109+
logger.info(f"Current mode: {mode}")
110+
111+
# Check if the message is a reply to another message
112+
if update.message.reply_to_message:
113+
replied_message = update.message.reply_to_message.text
114+
# Combine the user's message with the replied message
115+
user_message = f"Initial message from assistant: {replied_message}\nUser's new message: {user_message}"
116+
logger.info(f"Combined dialog: {user_message}")
105117

106118
# Store user info only if it's a private chat
107119
# if chat_type == "private":
@@ -115,7 +127,7 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
115127

116128
# Call OpenAI API
117129
language_code = user.language_code or "en" # Default to English if language_code is not provided
118-
bot_response = call_openai_api(user_message, language_code)
130+
bot_response = call_openai_api(user_message, language_code, command=mode)
119131

120132
# Send response back to the user or group
121133
await update.message.reply_text(bot_response)
@@ -131,6 +143,8 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
131143

132144
# Talk command handler
133145
async def talk(update: Update, context: ContextTypes.DEFAULT_TYPE):
146+
mode = "talk"
147+
context.user_data['mode'] = mode
134148
user = update.message.from_user
135149
chat_type = update.message.chat.type
136150

@@ -142,6 +156,54 @@ async def talk(update: Update, context: ContextTypes.DEFAULT_TYPE):
142156

143157
user_message = user_message[1] # Extract the message part
144158

159+
# Check if the message is a reply to another message
160+
if update.message.reply_to_message:
161+
replied_message = update.message.reply_to_message.text
162+
# Combine the user's message with the replied message
163+
user_message = f"Initial message from assistant: {replied_message}\nUser's new message: {user_message}"
164+
logger.info(f"Combined dialog: {user_message}")
165+
# print(f"Combined dialog: {user_message}")
166+
167+
# Store user info only if it's a private chat
168+
# if chat_type == "private":
169+
# store_user_info(user)
170+
171+
# Store user info
172+
store_user_info(user)
173+
174+
# Detect language from the user's message
175+
language_code = detect_language(user_message)
176+
177+
# Call OpenAI API
178+
language_code = user.language_code or "en" # Default to English if language_code is not provided
179+
bot_response = call_openai_api(user_message, language_code, command=mode)
180+
181+
# Send response back to the user or group
182+
await update.message.reply_text(bot_response)
183+
184+
# Prompt command handler
185+
async def prompt(update: Update, context: ContextTypes.DEFAULT_TYPE):
186+
mode = "prompt"
187+
context.user_data['mode'] = mode
188+
user = update.message.from_user
189+
chat_type = update.message.chat.type
190+
191+
# Extract the message after the /talk command
192+
user_message = update.message.text.split(maxsplit=1) # Split the message into command and text
193+
if len(user_message) < 2: # Check if there is no message after /talk
194+
await update.message.reply_text("Hey, you gotta give me something to work with! Try /prompt <your message>.")
195+
return
196+
197+
user_message = user_message[1] # Extract the message part
198+
199+
# Check if the message is a reply to another message
200+
if update.message.reply_to_message:
201+
replied_message = update.message.reply_to_message.text
202+
# Combine the user's message with the replied message
203+
user_message = f"Initial message from assistant: {replied_message}\nUser's new message: {user_message}"
204+
logger.info(f"Combined dialog: {user_message}")
205+
# print(f"Combined dialog: {user_message}")
206+
145207
# Store user info only if it's a private chat
146208
# if chat_type == "private":
147209
# store_user_info(user)
@@ -154,7 +216,7 @@ async def talk(update: Update, context: ContextTypes.DEFAULT_TYPE):
154216

155217
# Call OpenAI API
156218
language_code = user.language_code or "en" # Default to English if language_code is not provided
157-
bot_response = call_openai_api(user_message, language_code)
219+
bot_response = call_openai_api(user_message, language_code, command=mode)
158220

159221
# Send response back to the user or group
160222
await update.message.reply_text(bot_response)
@@ -170,6 +232,7 @@ def main():
170232
# Handlers
171233
application.add_handler(CommandHandler("start", start))
172234
application.add_handler(CommandHandler("talk", talk))
235+
application.add_handler(CommandHandler("prompt", prompt))
173236
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
174237

175238
# Start the bot

0 commit comments

Comments
 (0)