Skip to content

Instantly share code, notes, and snippets.

@b1oki
Created March 25, 2025 00:17
Show Gist options
  • Select an option

  • Save b1oki/1e30c6165ab7d0f12092e695bac61fad to your computer and use it in GitHub Desktop.

Select an option

Save b1oki/1e30c6165ab7d0f12092e695bac61fad to your computer and use it in GitHub Desktop.
Hugging Face API
HF_API_URL = "https://api-inference.huggingface.co/models/"
HF_API_TOKEN = os.getenv("HF_API_TOKEN") # Токен Hugging Face
HF_MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.3"
HF_GENERATION_SETTINGS = {
"max_length": 100,
"do_sample": True,
"top_p": 0.95,
"temperature": 0.9,
"repetition_penalty": 1.2,
}
TRIGGER_PROBABILITY = 0.15 # 15% шанс ответа на сообщение
# Саркастичные фразы
SARCASTIC_PHRASES = [
"О, великий оратор изволил высказаться...",
"О, великий мыслитель изволил высказаться!",
"О, великий мыслитель сказал:",
"О, смотрите кто заговорил...",
"Великая мудрость от эксперта:",
"Продолжайте, мне нравится ваша наивность!",
"Позвольте мне записать это... нет, не буду.",
"Кто-то сегодня проглотил словарь сарказма!",
"Ах, вот оно что...",
"Ну конечно, ведь все знают, что",
"Ну конечно, ведь мы все тут:",
"*зевает* И что?",
"Это всё? Серьёзно?",
"Спасибо, кэп!",
]
def generate_text(prompt):
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
payload = {
"inputs": prompt,
"parameters": HF_GENERATION_SETTINGS
}
response = requests.post(HF_API_URL + HF_MODEL_NAME, headers=headers, json=payload)
return response.json()[0]['generated_text']
def handle_sret_shot_ai_bot(update):
bot = telegram_sret_shot_ai_bot
if 'message' not in update:
return 'OK'
message_data = update['message']
chat_id = message_data['chat']['id']
chat_type = message_data['chat']['type']
message_id = message_data['message_id']
try:
# для отладки шлём админку сообщение
bot.sendMessage(telegram_admin_chat_id, f"update:\n{update}")
bot.forwardMessage(telegram_admin_chat_id, chat_id, message_id)
if 'text' not in message_data:
return 'OK'
# chat_type == 'supergroup'
if random.random() < TRIGGER_PROBABILITY and chat_type != 'private':
user_text = message_data['text']
if 'first_name' in message_data['from']:
user_name = message_data['from']['first_name']
elif 'username' in message_data['from']:
user_name = message_data['from']['username']
else:
if random.random() < 0.5:
user_name = 'лопух'
else:
user_name = 'чмошник'
prompt = f"{random.choice(SARCASTIC_PHRASES)} {user_text}"
bot_response = generate_text(prompt)
bot.sendMessage(telegram_admin_chat_id, f"bot_response:\n{bot_response}")
bot_response = bot_response.replace(prompt, '').strip()
bot_response = bot_response.replace(user_text, '').strip()
# Иногда добавляем оскорбление
if random.random() < 0.3:
if random.random() < 0.5:
bot_response += f"\n\nP.S. {user_name}, ты как всегда на высоте... своей глупости."
else:
bot_response += f"\n\nP.S. {user_name}, ты сегодня особо невыносим."
if 'is_premium' in message_data['from'] and message_data['from']['is_premium'] and random.random() < 0.3:
if random.random() < 0.5:
bot_response += f"\n\nP.S. {user_name}, ты как всегда на высоте... своей глупости."
else:
bot_response += f"\n\nP.S. {user_name}, ты сегодня особо невыносим."
bot.sendMessage(chat_id, bot_response)
bot.sendMessage(telegram_admin_chat_id, bot_response)
except Exception as e:
bot.sendMessage(telegram_admin_chat_id, f"Traceback:\n{traceback.format_exc()}")
bot.sendMessage(telegram_admin_chat_id, f"Exception:\n{e}",)
bot.sendMessage(telegram_admin_chat_id, f"Exception dict:\n{e.__dict__}", )
# if random.random() < 0.5:
# bot.sendMessage(chat_id, "*делает вид, что занят важными делами*")
# else:
# bot.sendMessage(chat_id, "*делает вид, что не слышал*")
return 'OK'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment