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

Ошибка в коде на пайтоне

dasd dsad Ученик (78), открыт 1 неделю назад
Exception has occurred: TypeError
object Queue can't be used in 'await' expression
File "C:\Users\admin\Desktop\import logging.py", line 167, in main
await updater.start_polling()
File "C:\Users\admin\Desktop\import logging.py", line 173, in <module>
asyncio.run (main())
~~~~~~~~~~~^^^^^^^^
TypeError: object Queue can't be used in 'await' expression
сама ошибка,код будет ниже. Токен я скрыл.
Дополнен 1 неделю назад
 import logging
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode
from telegram.ext import (
Updater,
CommandHandler,
CallbackContext,
CallbackQueryHandler,
MessageHandler,
Filters,
)
import asyncio

# Configure logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)

# Your bot's token (replace with your actual token)
TOKEN = "Типо скрыл"

# Define available prefixes and their corresponding titles
PREFIXES = {
"admin": "Администратор",
"moderator": "Модератор",
"vip": "VIP",
}

# Store prefix assignments (chat_id -> user_id -> prefix)
prefix_assignments = {}


async def is_admin(update: Update, context: CallbackContext) -> bool:
"""Checks if the user is an administrator in the chat."""
try:
member = await context.bot.get_chat_member(
update.effective_chat.id, update.effective_user.id
)
return member.status in ["administrator", "creator"]
except Exception as e:
logging.error(f"Error checking admin status: {e}")
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Произошла ошибка при проверке прав администратора: {e}",
)
return False


Дополнен 1 неделю назад
async def set_prefix(update: Update, context: CallbackContext, prefix_key: str):
"""Assigns a prefix to a user in the chat."""
chat_id = update.effective_chat.id
user_id = update.effective_user.id
prefix_title = PREFIXES.get(prefix_key)

if not prefix_title:
await context.bot.send_message(
chat_id=update.effective_chat.id, text="Неверный префикс."
)
return

try:
await context.bot.set_chat_administrator_custom_title(
chat_id=chat_id, user_id=user_id, custom_title=f"[{prefix_title}]"
)
prefix_assignments.setdefault(chat_id, {})[user_id] = prefix_title
await context.bot.send_message(
chat_id=chat_id,
text=f"Префикс *{prefix_title}* назначен!",
parse_mode=ParseMode.MARKDOWN,
)
except Exception as e:
logging.error(f"Error setting prefix: {e}")
await context.bot.send_message(
chat_id=chat_id, text=f"Ошибка при назначении префикса: {e}"
)


async def remove_prefix(update: Update, context: CallbackContext):
Дополнен 1 неделю назад
     """Removes the prefix from a user in the chat."""
chat_id = update.effective_chat.id
user_id = update.effective_user.id

try:
await context.bot.set_chat_administrator_custom_title(
chat_id=chat_id, user_id=user_id, custom_title=""
)
prefix_assignments.get(chat_id, {}).pop(user_id, None)
await context.bot.send_message(
chat_id=chat_id, text="Префикс удален!", parse_mode=ParseMode.MARKDOWN
)
except Exception as e:
logging.error(f"Error removing prefix: {e}")
await context.bot.send_message(
chat_id=chat_id, text=f"Ошибка при удалении префикса: {e}"
)


async def pref_handler(update: Update, context: CallbackContext):
"""Handles the /pref command, allowing admins to choose prefixes."""
if not await is_admin(update, context):
return

keyboard = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text=f"[{PREFIXES[key]}]", callback_data=f"set_prefix_{key}"
)
for key in PREFIXES
],
[InlineKeyboardButton(text="Удалить префикс", callback_data="remove_prefix")],
]
)
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="Выберите префикс:",
reply_markup=keyboard,
)
Дополнен 1 неделю назад
 async def handle_message(update: Update, context: CallbackContext):
"""Handles regular messages, adding prefixes if assigned."""
chat_id = update.effective_chat.id
user_id = update.effective_user.id
message_text = update.effective_message.text

prefix_title = prefix_assignments.get(chat_id, {}).get(user_id)
if prefix_title:
await context.bot.send_message(
chat_id=chat_id,
text=f"[{prefix_title}] {message_text}",
parse_mode=ParseMode.MARKDOWN,
reply_to_message_id=update.message.message_id,
)


async def handle_callback_query(update: Update, context: CallbackContext):
"""Handles callback queries from inline buttons."""
query = update.callback_query
if not query:
return

try:
data = query.data
if data.startswith("set_prefix_"):
prefix_key = data.split("_")[1]
await set_prefix(update, context, prefix_key)
elif data == "remove_prefix":
await remove_prefix(update, context)
await query.answer() # Acknowledge the query
await context.bot.edit_message_reply_markup(
Дополнен 1 неделю назад
chat_id=query.message.chat_id, message_id=query.message.message_id
)

except Exception as e:
logging.error(f"Error handling callback query: {e}")
await query.answer(text="Произошла ошибка.")


async def main():
"""Main function to run the bot."""
updater = Updater(TOKEN, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("pref", pref_handler))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message))
dispatcher.add_handler(CallbackQueryHandler(handle_callback_query))
await updater.start_polling()
updater.idle()


if __name__ == "__main__":
logging.info("Starting bot...")
asyncio.run(main())
1 ответ
Николай Кондрашкин Мастер (1962) 1 неделю назад
убери await преред updater.start_polling() в методе main()
Похожие вопросы