I keep getting the error whenever I run my code:
bot running ... Traceback (most recent call last): File "winners_bot.py", line 53, in <module> asyncio.run(main()) File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "winners_bot.py", line 50, in main async with client: AttributeError: __aenter__ How can I fix it? Here is my code here:
import random import discord from datetime import datetime, timedelta from config import DISCORD_BOT_TOKEN, COMMAND_CHANNEL_ID, MESSAGE_CHANNEL_ID, ADMIN_IDS, AVOID_ROLES_IDS import asyncio intents = discord.Intents.all() client = discord.Client(intents=intents) print("bot running ...") @client.event async def on_ready(): activity = discord.Activity(name = "with winners", type = discord.ActivityType.playing) await client.change_presence(status=discord.Status.online, activity=activity) @client.event async def on_message(message): if message.content.startswith('!pick ') and message.channel.id == COMMAND_CHANNEL_ID and message.author.id in ADMIN_IDS: message_split = (message.content).split() #arg1 scrape_channel = str(message_split[1]) scrape_channel = scrape_channel[scrape_channel.find('<#')+len('<#'):scrape_channel.rfind('>')] scrape_channel = client.get_channel(int(scrape_channel)) messages = await scrape_channel.history(after=datetime.utcnow()-timedelta(days=1)).flatten() while True: staff = 0 #pick random message random_message = random.choice(messages) for role in random_message.author.roles: if role.id in AVOID_ROLES_IDS: staff = 1 #staff detected, ignoring the message if staff == 1: pass elif staff == 0: if len(str(random_message)) > 5: channel = client.get_channel(MESSAGE_CHANNEL_ID) embed=discord.Embed(title=":tada::tada: Winner: {} :tada::tada:".format(random_message.author.name), description="<@{}>\n**Message:** '{}'".format(random_message.author.id, random_message.content), color=0xFF0000) embed.set_author(name="Random Message Picker") await channel.send(embed=embed) break async def main(): async with client: await client.start(DISCORD_BOT_TOKEN) asyncio.run(main()) 32 Answers
removed async with client and it worked as mentioned by dirn above
2I got the same error in httpx and trio. there are two clients of httpx are httpx.client() and httpx.AsyncClient(). make sure you use it correctly
Synchronous API by default:
with httpx.Client() as client: r = client.get(') To make asynchronous requests, you need to use AsyncClient():
import httpx import trio async def main(): async with httpx.AsyncClient() as client: response = await client.get(') print(response) trio.run(main)