Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Проблема с кодом на python

Frelinq Знаток (414), на голосовании 1 месяц назад
Здравствуйте не работает функция мута код ниже!

 import telebot 
import time
import re

BOT_TOKEN = 'YOUR_BOT_TOKEN' # Replace with your bot token
bot = telebot.TeleBot(BOT_TOKEN)

MUTED_USERS = {}


def mute_user(message, user_id, duration_str):
try:
duration_parts = re.match(r"(\d+)\s*(минут|часов|дней)", duration_str.lower())
if not duration_parts:
raise ValueError("Неверный формат времени.")

duration_value = int(duration_parts.group(1))
duration_unit = duration_parts.group(2).lower()
duration_seconds = {
"минут": duration_value * 60,
"часов": duration_value * 60 * 60,
"дней": duration_value * 60 * 60 * 24
}.get(duration_unit)

if duration_seconds is None:
raise ValueError("Неверная единица времени.")

unmute_time = time.time() + duration_seconds
MUTED_USERS[user_id] = unmute_time

try:
replied_user = message.reply_to_message.from_user
username = replied_user.username
if not username:
raise ValueError("Username not found for the replied user.")
bot.reply_to(message, f"Пользователь @{username} замучен на {duration_value} {duration_unit}.")
except AttributeError:
bot.reply_to(message, "Ошибка: Не удалось определить пользователя для мута. Убедитесь, что вы отвечаете на сообщение.")
except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except telebot.apihelper.ApiException as e:
bot.reply_to(message, f"Ошибка Telegram API: {e.description}")
except Exception as e:
bot.reply_to(message, "Произошла неизвестная ошибка при отправке сообщения.")

except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except Exception as e:
bot.reply_to(message, "Произошла неизвестная ошибка.")


@bot.message_handler(func=lambda message: True)
def handle_message(message):
if message.reply_to_message and message.text.lower().startswith("мут"):
try:
duration_str = message.text.lower().replace("мут", "").strip()
mute_user(message, message.reply_to_message.from_user.id, duration_str)
except Exception as e:
bot.reply_to(message, f"Ошибка: {e}")


@bot.message_handler(content_types=['text'])
def handle_muted_message(message):
if message.from_user.id in MUTED_USERS and time.time() < MUTED_USERS[message.from_user.id]:
bot.delete_message(message.chat.id, message.message_id)
bot.reply_to(message, "Ты замучен!")


bot.infinity_polling()
когда пишу мут в журнале пишеться это
 2024-12-07 03:39:41,209 - __main__ - INFO - Message received from user 7688316019: мут @username 1 час 
после этого ничего не происходит
Голосование за лучший ответ
꧁❤༺♥P͎ ͎D͎i͎d͎d͎y͎♥༻❤꧂ Мастер (2231) 2 месяца назад
В чат жпт забей да и все
FrelinqЗнаток (414) 2 месяца назад
в том и дело что код этот из нейронки
Frelinq Знаток (414) Дмитрий Домов, типа я делаю на основе нейронки и типа иногда случаеться это и мне приходиться самому решать как то
Cogni Просветленный (46614) 2 месяца назад
 import telebot  
import time
import re
from threading import Thread

BOT_TOKEN = 'YOUR_BOT_TOKEN' # Замените на ваш токен бота
bot = telebot.TeleBot(BOT_TOKEN)

MUTED_USERS = {}

def unmute_user(user_id):
time.sleep(MUTED_USERS[user_id] - time.time())
del MUTED_USERS[user_id]

def mute_user(message, user_id, duration_str):
try:
# Обновленное регулярное выражение
duration_parts = re.match(r"(\d+)\s*(минут(?:а|ы)?|час(?:ов|а)?|дней)", duration_str.lower())
if not duration_parts:
raise ValueError("Неверный формат времени.")

duration_value = int(duration_parts.group(1))
duration_unit = duration_parts.group(2).lower()

# Преобразование единиц времени в секунды
if "минут" in duration_unit:
duration_seconds = duration_value * 60
elif "час" in duration_unit:
duration_seconds = duration_value * 60 * 60
elif "дней" in duration_unit:
duration_seconds = duration_value * 60 * 60 * 24
else:
raise ValueError("Неверная единица времени.")

unmute_time = time.time() + duration_seconds
MUTED_USERS[user_id] = unmute_time

# Запуск потока для автоматического размутирования
Thread(target=unmute_user, args=(user_id,)).start()

try:
replied_user = message.reply_to_message.from_user
username = replied_user.username
if not username:
raise ValueError("Username не найден для отвеченного пользователя.")
bot.reply_to(message, f"Пользователь @{username} замучен на {duration_value} {duration_unit}.")
except AttributeError:
bot.reply_to(message, "Ошибка: Не удалось определить пользователя для мута. Убедитесь, что вы отвечаете на сообщение.")
except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except telebot.apihelper.ApiException as e:
bot.reply_to(message, f"Ошибка Telegram API: {e.description}")
except Exception as e:
bot.reply_to(message, "Произошла неизвестная ошибка при отправке сообщения.")

except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except Exception as e:
bot.reply_to(message, "Произошла неизвестная ошибка.")

@bot.message_handler(func=lambda message: True)
def handle_message(message):
if message.reply_to_message and message.text.lower().startswith("мут"):
try:
duration_str = message.text.lower().replace("мут", "").strip()
mute_user(message, message.reply_to_message.from_user.id, duration_str)
except Exception as e:
bot.reply_to(message, f"Ошибка: {e}")

@bot.message_handler(content_types=['text'])
def handle_muted_message(message):
if message.from_user.id in MUTED_USERS and time.time() < MUTED_USERS[message.from_user.id]:
try:
bot.delete_message(message.chat.id, message.message_id)
bot.reply_to(message, "Ты замучен!")
except telebot.apihelper.ApiException as e:
print(f"Ошибка при удалении сообщения: {e}")

bot.infinity_polling()
Анонимус Просветленный (30817) 2 месяца назад
Проблема в том, что вы используете bot.delete_message в handle_muted_message, но не проверяете, имеет ли бот права на удаление сообщений в данном чате. Боты по умолчанию не имеют таких прав. Пользователь должен дать боту соответствующие разрешения.
 import telebot 
import time
import re

BOT_TOKEN = 'YOUR_BOT_TOKEN' # Replace with your bot token
bot = telebot.TeleBot(BOT_TOKEN)

MUTED_USERS = {}


def mute_user(message, user_id, duration_str):
try:
# ... (Эта часть кода остается без изменений) ...

try:
replied_user = message.reply_to_message.from_user
username = replied_user.username
if not username:
raise ValueError("Username not found for the replied user.")
bot.reply_to(message, f"Пользователь @{username} замучен на {duration_value} {duration_unit}.")
except AttributeError:
bot.reply_to(message, "Ошибка: Не удалось определить пользователя для мута. Убедитесь, что вы отвечаете на сообщение.")
except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except telebot.apihelper.ApiException as e:
bot.reply_to(message, f"Ошибка Telegram API: {e.description}")
except Exception as e:
bot.reply_to(message, f"Произошла неизвестная ошибка при отправке сообщения: {e}")

except ValueError as e:
bot.reply_to(message, f"Ошибка: {e}")
except Exception as e:
bot.reply_to(message, f"Произошла неизвестная ошибка: {e}")


@bot.message_handler(func=lambda message: True)
def handle_message(message):
if message.reply_to_message and message.text.lower().startswith("мут"):
try:
duration_str = message.text.lower().replace("мут", "").strip()
mute_user(message, message.reply_to_message.from_user.id, duration_str)
except Exception as e:
bot.reply_to(message, f"Ошибка: {e}")


@bot.message_handler(content_types=['text'])
def handle_muted_message(message):
if message.from_user.id in MUTED_USERS and time.time() < MUTED_USERS[message.from_user.id]:
try:
chat_member = bot.get_chat_member(message.chat.id, bot.get_me().id)
if chat_member.can_delete_messages:
bot.delete_message(message.chat.id, message.message_id)
bot.reply_to(message, "Ты замучен!")
else:
bot.reply_to(message, "Ты замучен! У меня нет прав на удаление сообщений в этом чате.")
except telebot.apihelper.ApiException as e:
bot.reply_to(message, f"Ошибка Telegram API: {e.description}")
except Exception as e:
bot.reply_to(message, f"Произошла неизвестная ошибка: {e}")


bot.infinity_polling()
Похожие вопросы