skip to Main Content

I got this error below after running my code that looks for messages in a Discord channel, and if it has an image it sends that image.

Anyone knows why and what I can do to fix it?

Traceback (most recent call last):
  File "/home/runner/discord-to-twitter/main.py", line 79, in <module>
    client.run(
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/7c2d4f13a93vf8xx548czn0v0hsgrrkv-python3-3.10.0/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/7c2d4f13a93vf8xx548czn0v0hsgrrkv-python3-3.10.0/lib/python3.10/asyncio/base_events.py", line 641, in run_until_complete
    return future.result()
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "/home/runner/discord-to-twitter/venv/lib/python3.10/site-packages/discord/http.py", line 680, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0)
import discord
import tweepy
import requests
import imghdr
from PIL import Image
import shutil
import urllib
import os
from keep_alive import keep_alive

client2 = tweepy.Client(
    bearer_token=
    'my_token',
    consumer_key='my_token',
    consumer_secret='my_token',
    access_token='my_token',
    access_token_secret='my_token')

auth = tweepy.OAuth1UserHandler(
    'my_token',
    'my_token',
    'my_token',
    'my_token')

# Create the API object using the OAuth1 user handler
api = tweepy.API(auth)

# Create the discord client with the default intents
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


@client.event
async def on_message(message):
    # check if the message is in a server (not a DM) and not from the bot itself
    if message.guild and message.author != client.user:
        # get the channel object for the channel you want to monitor
        channel = client.get_channel(973613949935317023)
        # check if the message was sent in the specified channel
        if message.channel == channel:
            # get the list of attachments for the message
            attachments = message.attachments
            content = message.content
            author = message.author
            # check if the message has any attachments
            if attachments:
                # loop over the attachments
                for attachment in attachments:
                    # get the URL of the attachment
                    image_url = attachment.url

                    img = Image.open(requests.get(image_url, stream=True).raw)

                    if not os.path.exists('photo.png'):
                        # create the file if it doesn't exist
                        open('photo.png', 'a').close()

                    img.save('photo.png')
                    filename = 'photo.png'

                    # upload the file
                    media = api.media_upload(filename)
                    print(filename)
                    client2.create_tweet(
                        text=
                        '😈 {author} JUST made this at @leveragedevils! Join while you still can! We would love to have you! 😈                     #btc #eth #solnfts #crypto #stocks #money #levdevtrading #sol #nft',
                        media_ids=[media.media_id])

                # add a reaction to the user's message
                await message.add_reaction('✅')

                # respond to the user's message with "Tweeted!"
                await message.channel.send('Tweeted!')
                os.remove('photo.png')

keep_alive()
client.run("my_token")

I tried to search on the internet but didn’t find any solutions. I think it sends too many requests but I don’t know how to fix it.

2

Answers


  1. To integrate a cooroutine is recommended to check methods from Wait Primitives that waits until a certain task is performed. When generating too much requests an exception is raised when timeout is greater than limit, optionally it could be determined as a float value discord.Client(intents=intents, max_ratelimit_timeout=30.0).

    client.wait_until_ready()
    while not client.is_closed() and message.guild and message.author != client.user:
        channel = client.get_channel(ID)
        if message.channel == channel: pass
            # await asyncio.sleep(100) you could try asyncio.sleep
        channel.close()
    
    Login or Signup to reply.
  2. Your code is executed without errors.

    bot permissions (MESSAGE CONTENT INTENT allowed)
    discord permissions

    @client.event
    async def on_message(message):
        if message.guild and message.author != client.user:
            channel = client.get_channel(ID)
            if message.channel == channel:
                attachments = message.attachments
                content = message.content
                author = message.author
                print(author, content, attachments)
                if attachments:
                    for attachment in attachments:
                        image_url = attachment.url 
                        img = Image.open(requests.get(image_url, stream=True).raw) 
                        if not os.path.exists('photo.png'):
                            open('photo.png', 'a').close() 
                        img.save('photo.png')
                        filename = 'photo.png' 
                        await message.channel.send(await attachment.to_file())
                        file = discord.File(filename)
                        await message.channel.send(file=file, content="Message to be sent")
                    await message.add_reaction('✅')
                    await message.channel.send('Forwarded') 
    

    CMD output

    [2022-12-22 12:14:06] [INFO] discord.client: logging in using static token
    [2022-12-22 12:14:07] [INFO] discord.gateway: Shard ID None has connected to Gateway (Session ID).
    logged in as bot#
    [<Attachment id=idfilename='image.png' url='https://cdn.discordapp.com/attachments/image.png'>]
    photo.png
    

    the above example shows that is possibly to download and upload files, I just have take a screenshot on the channel and send it again from bot, what means that you have not established correctly discord permissions or maybe you need to wrap tweepy asynchronously.

    import asyncio
    import functools
    
    import tweepy  # type: ignore
    from tweepy import * 
    
    async def acall(f, *args, **kwargs):
        return await asyncio.get_running_loop().run_in_executor(
            None, lambda: f(*args, **kwargs)
        )
    
    
    def awrap(f):
        @functools.wraps(f)
        async def wrapper(*args, **kwargs):
            return await acall(f, *args, **kwargs)
    
        return wrapper 
    
    def create_aproxy_class(cls):
        class AsyncProxy:
            __name__ = cls.__name__
            __doc__ = cls.__doc__
    
            def __init__(self, *args, **kwargs):
                self.proxy = cls(*args, **kwargs)
    
            def __getattr__(self, attr):
                attr = getattr(self.proxy, attr)
                return awrap(attr) if callable(attr) else attr
    
        return AsyncProxy
    
    
    API = create_aproxy_class(tweepy.API)
    

    define api

    import atweepy
    
    async def upload(key, secret, access_token, access_token_secret):
        try:
            auth = atweepy.OAuthHandler(key, secret)
        except tweepy.TweepError:
            return
        auth.set_access_token(access_token, access_token_secret)
        api = atweepy.API(
            auth,
            retry_count=3,
            retry_delay=10,
            wait_on_rate_limit_notify=True,
            wait_on_rate_limit=True,
            compression=True,
        )
        return api
    

    you need to implement this to the bot

            if attachments:
                for attachment in attachments:
                    image_url = attachment.url 
                    img = Image.open(requests.get(image_url, stream=True).raw) 
                    if not os.path.exists('photo.png'):
                        open('photo.png', 'a').close() 
                    img.save('photo.png')
                    filename = 'photo.png'
                    # tweepy api
                    media = await api.media_upload(filename)
                    client2.create_tweet(text='text', media_ids=[media.media_id])   
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search