Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async with client: AttributeError: __aenter__ error

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())
like image 310
methuselah Avatar asked Jul 01 '26 12:07

methuselah


1 Answers

I 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('https://example.com')

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('https://www.example.com/')
        print(response)

trio.run(main)
like image 124
Ericgit Avatar answered Jul 04 '26 01:07

Ericgit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!