#discord-bots

1 messages · Page 297 of 1

mighty pilot
#

Funny thing, I actually have narcolepsy

#

I literally get home and pass out

final iron
#

Only reason I know about narcolespy is because of that series

#

The mysterious benedict society or smth

mighty pilot
#

But I enjoy doing some coding projects so I make time during the evening on my weekends. My little escape from commercial plumbing lmfao

potent mulch
#

Hi, there's a free hosting website?

#

(where can i add the code i made and run on a public/private server)

turbid condor
#

Free hosting isn't good

#

Since you are using shared ips

#

So if it gets banned all the bots stop working

gray junco
#

Can someone help please

slate swan
#

I'm trying to get before.channel, but it gives out a NoneType, although everything is fine with after.channel. How to fix it?

slate swan
naive briar
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

gray junco
gray junco
naive briar
meager rock
turbid condor
#

Seems like u are using pycord

turbid condor
#

But you are trying to app_commands that exist in discord.py

turbid condor
gray junco
turbid condor
#

I think in pycord it is slash_commmands

#

Tho not sure u should check the docs

slate swan
#

before.channel is None

#

Depending on the event it makes sense so yeah krShrug

smoky bane
#

hi everyone I want to create a python bot any useful resources to get started ???

smoky bane
upbeat mason
#
@client.command()
async def userinfo(ctx, *, member: discord.Member = None):
    if member is None:
        member = ctx.author

    embed = discord.Embed(title="User Info", color=discord.Color.blue())

    embed.set_thumbnail(url=member.avatar)
    embed.add_field(name="Username", value=member.name, inline=True)
    embed.add_field(name="ID", value=member.id, inline=True)
    embed.add_field(name="Status", value=member.status, inline=True)
    embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d"), inline=True)
    embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d"), inline=True)
    embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)

    # Send the user information as an embed
    await ctx.send(embed=embed)

the status always shows as offline, any clue?

turbid condor
#

You have presence intent enabled?

upbeat mason
#

i think so one sec

turbid condor
#

It's a privileged intent so check dev portal too

upbeat mason
#

@turbid condor

#

its enabled in dev portal

naive briar
#

!d discord.Member.status

unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead.
upbeat mason
#

wait

#

its working for dnd and online, not for idle

turbid condor
#

Hmm weird

#

Does it throw any error in terminal?

upbeat mason
#

lemme see

#

nope

turbid condor
#

Try printing the status in your terminal

#

Tho it's pretty weird that it doesn't show idle

upbeat mason
#

wait

#

i've figured it out i think, it isnt idle its me which is showing offline for some reason

#

why? idk

turbid condor
#

Welp if your status is invisible then it will show offline

upbeat mason
#

yeah but it isnt

turbid condor
#

Welp try using get_user or fetch_user method to get the status

#

Tho I'm not sure what causing that issue

#

But you can try the above two methods

#

To do that

upbeat mason
#

i guess i can try that

#

i give up

left dew
#

how can i run 2 tasks.loops at the same time without getting this error:

RuntimeError: Task is already launched and is not completed.```
lyric sigil
#

oh

#

I have this error when i click a button in my message :

    await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'
#

here is the code :

class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
#

only the command is working well

naive briar
#

In discord.py, interaction always come before the item in UI callbacks

lyric sigil
#

Its working thanks !

naive briar
mighty pilot
#

Oh gather won't do it?

naive briar
#

No

buoyant quail
#

What's the problem of just starting them like

task1.start()
task2.start()

That's the same as gathering

#

And the error is because he is trying to run the same task

naive briar
#

I think they were asking how to run the same task twice 🤷

buoyant quail
#
task1 = tasks.loop(...)(function)
task2 = tasks.loop(...)(function)

can work

very weird to run it twice though

mighty pilot
#

Oh I thought he was trying to run 2 tasks concurrently

slate swan
#

task2 = task1?

buoyant quail
eager mural
#

hello I have a problem with my code when I do !start [id] the bot does not connect thank you for helping me

#
import discord
from discord.ext import commands

 
active_bots = {}

 
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)

 
@bot.command()
async def start(ctx, id):
    # Vérifiez si le bot avec l'ID donné n'est pas déjà actif
    if id not in active_bots:
        bot_instance = start_bot(id)
        if bot_instance:
            active_bots[id] = bot_instance
            await ctx.send(f"Bot {bot_instance.user.name} démarré avec succès!")
        else:
            await ctx.send("Impossible de démarrer le bot avec cet ID.")
    else:
        await ctx.send("Ce bot est déjà actif.")

  
@bot.command()
async def stop(ctx, id):
    # Vérifiez si le bot avec l'ID donné est actif
    if id in active_bots:
        stop_bot(active_bots[id])
        await ctx.send(f"Bot {active_bots[id].user.name} éteint avec succès!")
    else:
        await ctx.send("Ce bot n'est pas actif.")
 
def start_bot(id):
    try:
        with open("tokens.txt", "r") as file:
            tokens = file.read().splitlines()
            if id in tokens:
                bot_instance = commands.Bot(command_prefix='!', intents=intents)
                @bot_instance.event
                async def on_ready():
                    print(f'Connecté en tant que {bot_instance.user.name}!')
                bot_instance.run(id, bot=False)
                return bot_instance
            else:
                return None
    except Exception as e:
        print(f"Erreur lors du démarrage du bot : {str(e)}")
        return None

 
def stop_bot(bot):
    if bot:
        active_bots[bot.user.id].logout()
        del active_bots[bot.user.id]

# 
@bot.event
async def on_ready():
    print(f'Connecté en tant que {bot.user.name}')

# Lancer le bot
with open("YOUR_BOT_TOKEN.txt", "r") as token_file:
    bot.run(token_file.read().strip())
mighty pilot
#

Does it show any errors

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

eager mural
#

?

buoyant quail
#

You don't have message content intent

#

Message commands can't work without it

eager mural
#

aa

naive briar
buoyant quail
#

You should also get a warning about it

naive briar
#

Kinda sus if you ask me

buoyant quail
mighty pilot
#

Running multiple bots with the same code Norow

slate swan
#

bot=False was a method to run selfbot back in the days wasnt it

buoyant quail
#

yea

mighty pilot
#

This is definitely old selfbot code that I don't think will work anymore lol

buoyant quail
#

Looks more like some AI code

#

he deleted the comments from the code

slate swan
#

It wont but still selfbot is selfbot

lyric sigil
#

I have this error when trying to repress my button :

AttributeError: 'Button' object attribute 'disabled' is read-only
#
class MyView3(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
    @discord.ui.button(label="Click me to EXPRESS YOUR RAGE", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self , interaction , button):
        Button.label = "No more pressing!" # change the button's label to something else
        Button.disabled = True # set button.disabled to True to disable the button
        await interaction.response.send_message("**I am going to implode.**") # Send a message when the button is clicked

Here is the code

mighty pilot
#

Because you disabled the button

naive briar
lyric sigil
#

x) i changed it cuz it wasn't placed after async def so it was giving me error

#

so i was thinking i missed a caps

mighty pilot
#

No it needs to be lowercase

#

You also need to edit the original message with self to implement those changes

nova vessel
#

https://pastebin.com/WbRtMAHP

PS C:\Users\kiera\Desktop\CDC Discord Bot> & C:/Users/kiera/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/kiera/Desktop/CDC Discord Bot/main.py"
`import discord` import detected.  Interactions.py is a completely separate library, and is not compatible with d.py models.  Please see https://interactions-py.github.io/interactions.py/Guides/100%20Migration%20From%20D.py/ for how to fix your code.
Traceback (most recent call last):
  File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 5, in <module>
    class MyBot(commands.Bot):
  File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 9, in MyBot
    @commands.event
     ^^^^^^^^^^^^^^
AttributeError: module 'discord.ext.commands' has no attribute 'event'
PS C:\Users\kiera\Desktop\CDC Discord Bot>
vocal laurel
buoyant quail
nova vessel
#

I am pretty rookie at Python but I like to be ambitious

#

What am I doing wrong/what is causing this error?

buoyant quail
#

First of all discord.py and interactions shouldn't be used together. Choose one and use it

naive briar
nova vessel
buoyant quail
#

discord.py has slash commands :/
but you can use what you want

naive briar
#

discord.py already support slash commands since version 2.0

nova vessel
#

🤣

buoyant quail
#

About error - since you are subclassing the bot, you don't need event at all. on_ready is method of Bot class, just override it

nova vessel
#

I am trying to get into the practice of always using them but I am getting the feeling that it won't prove useful for this case

buoyant quail
#

It's strange to make commands methods of the bot

nova vessel
buoyant quail
#

ye

nova vessel
#

Okay

#

What would I be putting in the class? Just the slash commands and then when defying the functions, I do it outside of the class?

buoyant quail
#

Any extra functionality you'd add there or override. Like adding custom method to do bot.my_cool_method() or variable.
Or overriding methods like on_ready, on_message and so on

nova vessel
#

Okay

#

Thank you

gray junco
#

How to remove nix environment

#

It ruines my code

nova vessel
buoyant quail
nova vessel
#

Okay, thank you.

nova vessel
#

Is it the same as interactions?

buoyant quail
#

nope

nova vessel
#

Would this work below: (It was made using ChatGPT4 so I have something with my use case to refrence from.)

import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option

# Create a bot instance
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
slash = SlashCommand(bot, sync_commands=True)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @cog_ext.cog_slash(
        name="enlist",
        description="Enlist in the CDC.",
        options=[
            create_option(
                name="gamerscore",
                description="What is your gamerscore?",
                option_type=4,  # INTEGER
                required=True,
            ),
            create_option(
                name="name",
                description="What is CDC name going to be? It must be one word and be professional.",
                option_type=3,  # STRING
                required=True,
            ),
            create_option(
                name="division",
                description="What division would you like to join or work towards?",
                option_type=3,  # STRING
                required=True,
                choices=[
                    create_option(
                        name="Infantry",
                        value="Infantry"
                    ),
                    create_option(
                        name="Logistics",
                        value="Logistics"
                    ),
                    create_option(
                        name="Military Police",
                        value="Military Police"
                    )
                ]
            )
        ]
    )
    async def enlist(
        self,
        ctx: SlashContext,
        gamerscore: int,
        name: str,
        division: str
    ):
        member = ctx.author

        try:
            await member.edit(nick=f"E-1 | CDC {name}")
            if division == "Infantry":
                # Add role logic here
                pass
            elif division == "Logistics":
                m = "Logistics is currently unavailable. You have been assigned to Infantry."
                await ctx.send(m)
            elif division == "Military Police":
                # Add role logic here
                pass
            else:
                m = "Invalid division. Please choose from Infantry, Logistics, or Military Police."
                await ctx.send(m)
        except Exception as e:
            m = f"An error occurred: {str(e)}"
            await ctx.send(m)
        finally:
            m = "Welcome to the CDC! Make sure to introduce yourself, get familiar with the rules, and engrave yourself with the procedures."
            await ctx.send(m)

# Add the cog to the bot
bot.add_cog(MyCog(bot))

# Run the bot
bot.run('YOUR_BOT_TOKEN')
slate swan
#

Try it and see

tepid dagger
#

how do you set an embed's thumbnail to be the avatar of a user

slate swan
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
slate swan
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset) for the avatar the user has.

If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
gray junco
#

Guys

#

How to do options like thise on discord bot

#

Slash comamnd

golden portal
#

autocomplete

#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
golden portal
#

could also be Choices, hard to tell from that

gray junco
golden portal
#

sure, just know that autocomplete is dynamic, choices is static, so depends on your usecase

brazen skiff
#

What is the best module to make a discord bot in python which supports slash commands? And also pls link me any resources for that module so I can start working with it.

Also, I have a discord bot working with discord.py module. But it doesn't supprt slash commands because it was made 3 years ago. Is there any easy to make it use slash commands?

meager rock
#

if you want completely new environment then hikari with hikari lightbulb is a nice choice as well

normal lava
#

I made a bot having Instagram features but it's not growing 😔

brazen skiff
turbid condor
#

Choose whatever u feel comfortable with

golden portal
#

discord.py has a hybrid_command system that integrates slash commands behind the scenes, so you could use that if you already have a working bot

turbid condor
#

So it's depending on the use case

#

What if he wants only slash commands?

golden portal
#

Figured I would give another option, and tbh it's relatively easy to stop prefix with minimal effort

turbid condor
#

And care to tell how?

#

Just don't say disable message_content

golden portal
#

override on_message, don't use process_commands

turbid condor
#

Sometimes commands even work without processing in on_message event

buoyant quail
#

I believe discord.py has process commands only in on_message

turbid condor
#

Yeah but sometimes it doesn't need to be used

buoyant quail
#

What else processes them then?

mighty pilot
#

I haven't used webhooks yet but I'd like to. Is the typical use to create a webhook every time you want to send a message with it? Or check if there's one for that channel before creating one? Or what

golden portal
golden portal
#

It should be a webhook that the bot can use before creating

turbid condor
#

I'm just saying sometimes it isn't even needed and commands are working

#

Tho idk the reason for this happening

golden portal
#

it is required for it to work, that's literally where command processing came from

meager rock
golden portal
#

I feel like you're confused between listeners and events

turbid condor
#

Nope not confused I'm pretty sure about it

mighty pilot
#

So check for webhook, if there's not one for this channel create one and use it, else edit the existing and send message?

turbid condor
#

Cuz happened with me

#

Yeah but when expanded that code then i needed to process em

buoyant quail
#

You'd need provide a working code to prove that
Prefix commands won't work without it

golden portal
mighty pilot
#

Editing the webhook to match a user name and avatar. So multiple users can use the same webhook

golden portal
golden portal
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
mighty pilot
#

Oh well that makes it easier ig

#

Thanks

golden portal
#

welcome

tall temple
#

how to check how many people joined a server in a certain delay

buoyant quail
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
buoyant quail
#

Store the joined members in the way you want in that event

slate swan
#

You won't find docs for some random code

final iron
#

!d discord.Member.ban

unkempt canyonBOT
#

await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban).
final iron
#

^^^

eager mural
#

ty

brazen skiff
#

Is there any working code for a music bot with slash commands using disnake?

shrewd apex
graceful otter
#

Olá desenvovedores

#

↑^^↑

brazen skiff
graceful otter
#

Olá

turbid condor
brazen skiff
turbid condor
#

You can make that in dpy too

#

Shouldn't be that hard

glad cradle
turbid condor
#

Tbh i don't see the reason to change your entire to disnake

glad cradle
#

yeah that's true

turbid condor
#

And i won't say any lib is better over the other

#

Since it's all about preference

glad cradle
#

mh but some things are implemented better

mighty pilot
#

Anybody familiar with regex?

@bot.event
async def on_message(message):
    msg = message.content.split()
    lgth = len(msg)
    rand = random.sample(msg, lgth)
    rand = str(rand)
    
    content = str(rand).replace("[","").replace("]","")
    content = re.sub(r"(?s:'(.*)')\Z", r'\1', content)```

Trying to jumble someone's message and send it, but I need to remove the apostrophe before and after every word but not the ones inside the word. This works if a single word is sent but if there's multiples, it only removes the first and last one and idk how to get where I'm trying to go at this point
buoyant quail
#

Show example text and result

mighty pilot
#

Example text
example' 'text

#

Would it work if I iterate over each word?

buoyant quail
#

Mm yeah

#

just strip("'") it seems

mighty pilot
#

Well if I use an apostrophe in a word such as that's then it goes in as "that\'s" so could I strip() something that doesn't exist if that's not the case?

#

Because that's why I was using regex, it mixes ' and " based on the input

buoyant quail
#

strip will do nothing if it doesn't find the character you gave it

mighty pilot
#

And will it strip the ones in the middle of the words

buoyant quail
#

no

mighty pilot
#

Then I'll use that lol thanks

#

Regex is a nightmare

gray junco
#

Pls help guys the pycord server doesnt help me

quick brook
gray junco
quick brook
slate swan
#

Can you run this script and show what it returns? print(__import__("discord").__copyright__)

hushed galleon
#

pycord should have an abc module so it looks like a broken install; perhaps you installed both discord.py and py-cord and then uninstalled discord.py?

#

that did reproduce the error for me actually ```py

pip install discord.py py-cord
pip uninstall discord.py
py -c "from discord.commands import option"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "\site-packages\discord\commands_init_.py", line 26, in <module>
from .context import *
File "\site-packages\discord\commands\context.py", line 29, in <module>
import discord.abc
ModuleNotFoundError: No module named 'discord.abc'```

#

so er, uninstall any other discord package you might have then reinstall py-cord

slate swan
#

Anyone knows how I can fix this??

wicked atlas
#

your bot token is probably not the name of an environment variable

wicked atlas
#

have you set an enviroment variable with your token in it?

slate swan
wicked atlas
#

yeah whatever replit calls it

slate swan
#

Thanks for reminding me lmaoo

glad cradle
#

regenerate your token now @slate swan

slate swan
#

I did it before I send this

#

Do I replace ‘BOT_TOKEN’ with the token or

#

Do I remove the [ aswell

wicked atlas
#

no, you create an enviroment variabled named "BOT_TOKEN" and set it's value to the token

wicked atlas
#

the point of it is to not include your token in the code

slate swan
#

I mean for this command

wicked atlas
#

yeah

slate swan
#

So in the value I put token?

wicked atlas
#

you put your token, yes

slate swan
slate swan
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

Where it says you need to set the intents…

wicked atlas
#

what about it?

#

ah

slate swan
#

Everything

wicked atlas
#

you should be able to just use the intents object it creates there as an example, there are a few other intents that are disabled by default that you can enable if you need them

slate swan
#

I mean the code

wicked atlas
#

intents basically tell discord what events to send to your bot

slate swan
#

I already enabled the intents

wicked atlas
#

yes, but you need to enable them in your code like shown in that embed

woven dew
wicked atlas
#

embed code formatting is a little wack it looks like so

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)
slate swan
#

I have no clue ?

#

This is the code itself

wicked atlas
#

just create you intents variable somewhere before the bot variable is created

from discord import Intents
intents = Intents.default()
intents.message_content = True

then pass that variable into the definiton for your bot (line 16)

bot = commands.Bot(command_prefix="!", intents=intents)
slate swan
#

Can you speak in a way a dumba** would understand 💀

wicked atlas
#

ooga booga copy paste first code before line 16 then on whatever line that is now put , intents=intents inside the parenthesis like shown in the second codeblock

wicked atlas
#

halfway there

woven dew
#

put , intents=intents into parens on line 19

dusk dagger
slate swan
dusk dagger
#

who writes comments like that

slate swan
#

I think it’s a free source

#

It just guides you

slate swan
woven dew
#

add

wicked atlas
slate swan
#

Would it be like this?

woven dew
#

🥳

#

why are you writing discord bot if you have no idea how to write even simple code?

wicked atlas
#

except it was javascript 💀

woven dew
#

you have some shitty code at line 49

slate swan
#

Wait wrong error

woven dew
#

show your code

slate swan
slate swan
woven dew
slate swan
#

Ohh

woven dew
#

you have to save your code, u know?

#

this is not interesting

#

also, line 45 wont work

slate swan
woven dew
#

dont copy code from random sources, learn docs and make it yourself

slate swan
woven dew
#

i would rewrite this code completely

final iron
#

You’re missing the arg intents

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
slate swan
#

So I have no idea what to do here

final iron
slate swan
slate swan
final iron
#

Basic OOP

slate swan
final iron
#

Nowhere, it’s not a command

#

You also already have an instance of commands.Bot

#

You just need to pass the intents arg

#

This is extremely simple

slate swan
final iron
#

I don’t spoon feed

slate swan
slate swan
#

Traceback (most recent call last):
File "main.py", line 45, in <module>
bot.loop.create_task(send_custom_message())
File "/home/runner/SleepyMoralDeveloper/venv/lib/python3.10/site-packages/discord/client.py", line 140, in getattr
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

hallow kernel
#

Yep my solution will work

slate swan
#
@bot.loop(seconds=1)
async def loop_1():
    await send_custom_message()

@bot.event
async def on_ready(ctx):
    loop_1.start()
    ...
#

This would be it?

#

How would I use the achryonisis main function and pass it?

hallow kernel
#
@bot.loop(seconds=530)
async def send_custom_message():
    ...
    # same code, but change 
    while not bot.is_closed():
    # to
    if not bot.is_close():
        # and remove
        await asyncio.sleep(530)

# add this thing on line 43
@bot.event
async def on_ready(ctx):
    send_loop = send_custom_text.start()

# and remove thing that is on line 45
slate swan
#

Like this?

#

Got this error lol

hallow kernel
# slate swan

Remove line 47
Add colon (:) to the end of line 39
Add @bot.loop(seconds=530) after line 34

slate swan
hallow kernel
#

Sorry
Replace

@bot.loop(seconds=530) 

With

@tasks.loop(seconds=530)

And add to start of the file

from discord.ext import tasks
slate swan
#

You mean in the beginning like first line

#

I add From discord.ext import tasks

hallow kernel
slate swan
hallow kernel
slate swan
#

So I change from discord.txt to that?

slate swan
hallow kernel
slate swan
#

Done

#

Let me try

slate swan
hallow kernel
# slate swan

And i see that you already have on_ready() function

hallow kernel
# slate swan

Uh shuhh forgot, you don't need ctx in brackets....

slate swan
hallow kernel
#

So just add

send_custom_text.start()

To your on_ready function,
And remove that i asked to add

slate swan
#

Hold on I’m confused ?

hallow kernel
#

Doesn't matter, just inside of it

slate swan
#

Line 23?

hallow kernel
#

After it will be okay

slate swan
#

So hold on ? I add this where ? send_custom_text.start()

slate swan
hallow kernel
slate swan
#

So between the parenthesis ?

#

Or after it

hallow kernel
#

Like code that will be executed

slate swan
hallow kernel
#
@bot.event
async def on_ready():
    send_custom_message.start()
    print(f'We have logged in as {bot.user}')
slate swan
#

I’m guessing like this?

hallow kernel
#

And it's message, not text... Oh i am sleepy..

slate swan
#

so send_custom_message.start()

hallow kernel
#

Yes
And right indentation.. (spaces)

slate swan
#

Would this be fine ??

#

( I replaced the text with message )

hallow kernel
#

And removed extra space before that?

slate swan
hallow kernel
#

You still have extra space on start of line 24

slate swan
hallow kernel
#

Not all of them!

#

Just standard python syntax
....

slate swan
#

Like this?

hallow kernel
#

24 and 25 should start on same column..

slate swan
#

So same line?

hallow kernel
#

No

#

Like standard python syntax

slate swan
hallow kernel
#

Same number of spaces before ... Oh just figure it out by yourself.

There are few stupid mistakes, code should work if you fix them

#

And became friends with OOP style

#

Im going to sleep, bye

slate swan
hallow kernel
#

Send screenshot of last part of code

slate swan
#

At the end?

hallow kernel
#

Remove lines
46, 45, 44

hallow kernel
slate swan
hallow kernel
#

Ok it for some reason doesn't know who is server

slate swan
hallow kernel
#

I suppose

slate swan
hallow kernel
#

It can't find server with that id

#

(from line 38)

slate swan
#

Ohh

#

I forgot to put my server Guild there

slate swan
#

Still the same

slate swan
hallow kernel
#

Check if that id is right

slate swan
#

1147111605650325617

#

Seems right to me

hallow kernel
#

And if bot accaunt is in that server

slate swan
hallow kernel
slate swan
#

Just added it

hallow kernel
#

Change to is_closed then idk....

slate swan
#

Sorry, what?

hallow kernel
#

||I should get money for that kind of help||
Anyway, 2:23am, i am going to sleep, if you need help find someone else

slate swan
#

Or maybe even fix it yourself shrug

slate swan
hallow kernel
#

I will just leave

slate swan
hallow kernel
# slate swan Neither do I lol

You can learn python basics, and start to slightly understand what are you trying to do by yourself, or with help, here should be ton of people who want to help you to learn

#

But keyword is learn

slate swan
mighty pilot
hallow kernel
#

With all steps, like checking documentations, experiments, and etc.

mighty pilot
#

The error tells you exactly what is wrong

#

Your bot has no attribute named is_close

slate swan
#

Oh I just change it to “if not bot.is_close”

slate swan
mighty pilot
#

Is_close does not exist

hallow kernel
mighty pilot
#

Delete lines 40 and 41, take 4 spaces out of line 42.

hallow kernel
slate swan
mighty pilot
scenic pike
#

Any who can teach me how can i make invite tracker bot?

mighty pilot
#

Hence the unexpected indent

slate swan
hallow kernel
mighty pilot
# slate swan

Make it look like this, but move line 41 to the left a bit

slate swan
#

Oh sh*t did I delete it ?

slate swan
mighty pilot
#

Did you?

slate swan
#

I think so 💀

mighty pilot
#

Welp, time to scrap it Idkchu

slate swan
#

Here is what it was before

mighty pilot
#

Again, line 41.... 4 spaces.... to the left

slate swan
#

I just deleted it fuck

#

Oh my goodness

mighty pilot
#

Alright I got a child to put to sleep. Good luck!

severe sonnet
#

okay guys

#

a friend recomended replit

#

anyone here knows how to use replit vps?

#

that is 24/07?

slate swan
mighty pilot
#

I recommend anything but replit

slate swan
#

It’s a different one

mighty pilot
#

I advise against sharing a bot token in a public forum

slate swan
#

Before I even sent it

#

But with a new error I managed to add it back

slate swan
mighty pilot
#

Await needs to match indentation level of the 'channel' above it

slate swan
#

Done

mighty pilot
#

Do you know what I mean when I say indentation level

mighty pilot
#

If you draw a line vertical down from where it says channel. The first letters should be on the same vertical line

#

You know, you've been here 3 hours now and I bet if you had read a python book or study guide for an hour you'd have this fixed an hour ago

slate swan
hallow kernel
#
import os
from discord.ext import tasks, commands
from discord import Intents


bot_token = os.environ['BOT_TOKEN']

class data:
    server_id = 1147111605650325617
    server = None
    channel_id = 1147944228522053713
    channel = None

intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='/', intents=intents)

@bot.event
async def on_ready():
    send_custom_message.start()
    print(f'We have logged in as {bot.user}')

@bot.command()
async def instagram(ctx, command: str, followers: int, url: str):
    response = f"Command:
{command}\nFollowers: {followers}\nURL: {url}"
    await ctx.send(response)

@tasks.loop(seconds=530)
async def send_custom_message():
    await data.channel.send('/instagram followers 250 https://instagram.com/negregro1')

@send_custom_message.before_loop
async def before_send_custom_message():
    await bot.wait_until_ready()
    data.server = bot.get_guild(data.server_id)
    data.channel = data.server.get_channel(data.channel_id)

if __name__=="__main__":
    bot.run(bot_token)

@mighty pilot check this

slate swan
#

You wrote the whole thing ??

mighty pilot
#

Yea it's not hard to write. This code is not complex at all

slate swan
#

Just for me bro Skull I honestly don’t deserve you bro 💀

severe sonnet
slate swan
#

So that’s it?

hallow kernel
mighty pilot
severe sonnet
#

thought it's one of the fewest that is 24/07

severe sonnet
#

since a friend could use it

hallow kernel
severe sonnet
#

and plus this could be a temporary server for me since i can't pay for one

mighty pilot
slate swan
#

And paste this one in?

hallow kernel
#

Ask @mighty pilot

slate swan
#

I guess yes?

hallow kernel
#

I could misspell or mistake

mighty pilot
#

Lmao idk best way to see is to hit run

#

I'm just a hobbyist with ideas I like to see happen

severe sonnet
#
No such file: main.py
repl process died unexpectedly: exit status 2

Giving up. You can try again by clicking Run. You may need to fix the [interpreter] definition in the .replit file first.
severe sonnet
#

i don't know how to config properlhy

#

*properly

hallow kernel
slate swan
#

I ran it

hallow kernel
#

yea i misspeled

severe sonnet
#

this one:

slate swan
hallow kernel
slate swan
#

I just deleted the whole code

#

Fuck

hallow kernel
#

And i probably added new line after colon

slate swan
#

I FIXED IT

#

IM THE BEST DEVELOPER

#

ABSOLUTELY NO ONE HELPED ME

hallow kernel
severe sonnet
mighty pilot
#

Congrats you can copy and paste. Sometimes.

slate swan
hallow kernel
slate swan
#

What was the command btw?

severe sonnet
#

need more information?

hallow kernel
#

please Curome don't try to research that staff that you never saw, just because you feel so eager to knowledge. Just go sleep!!!

slate swan
#

For the automation

severe sonnet
#

also Curome, how do i contact the comunity of replit?

slate swan
#

@hallow kernel good night

mighty pilot
hallow kernel
mighty pilot
#

Better than no hours

slate swan
slate swan
#

Doesn’t work lol

mighty pilot
#

It won't pop up like a slash command

#

It's a text command

slate swan
#

Isn’t it better?

mighty pilot
#

Learn some stuff then come back

slate swan
#

Like this for example

twilit grotto
#

thats against instagram TOS & discord if i remember correctly.

mighty pilot
#

Yea ik, it's a whole different layout

slate swan
mighty pilot
#

Doesn't actually interface with insta

twilit grotto
#

botting statistics is against TOS 🤷‍♂️

slate swan
twilit grotto
#

Sure

mighty pilot
#

I'm not super familiar with the mumbo jumbo of all that, but it has no interactions with anything It's just a message that you manually edit

slate swan
#

@mighty pilot doesn’t pop up

mighty pilot
#

Is your bot in that channel

slate swan
mighty pilot
#

Idkchu learn some stuff

slate swan
#

Nvm but look

slate swan
# slate swan

if it doesnt bot then what does the command do then

final iron
slate swan
final iron
#

How does it violate TOS

slate swan
#

its a follow bot

final iron
#

huh

slate swan
#

you run a command with how many followers you want a page to receive

#

or thats how its supposed to work

mighty pilot
#

That's absolutely not what that code does lmao

slate swan
#

ive read zero code and all i see is "follow bot" with a guy passing in an ig handle and follower amount

mighty pilot
#

Then maybe look at some code? It takes his input and puts it into a message and sends that message every 530 seconds

mighty pilot
#

Idkchu sends a message every once in a while. Believe me, he's not writing anything fancy like a follow bot he was in here for 3 hours troubleshooting that basic code that someone else wrote

slate swan
#

instagram module: premium follow
quantity: 10
link: blah blah blah

mighty pilot
#

Yes it's poor design, and I told him not to send tokens right after that

slate swan
#

i feel someone is slightly altering their code so we dont see its full functionality

mighty pilot
#

Idk anything about it

mighty pilot
quick brook
#

any bot that just sends messages on a loop is spam

final iron
#

You shouldn't be running things in on_ready as well

hallow kernel
hallow kernel
quick brook
hallow kernel
hallow kernel
final iron
#

Subclass, run in setup_hook

final iron
hallow kernel
hallow kernel
final iron
#

on_ready can be called multiple times during setup, there's also no guarantee it'll be run after the bot connects

#

Discord also has a chance to disconnect you for making API calls during setup

#

tldr don't do shit in on_ready

real oriole
#

i have this script https://paste.pythondiscord.com/UR3Q wrong token btw and it sends this error who can help? I need some hours so if there is any questions feel free to hop on my dms and ask and ill answer later

sick birch
vale wing
#

That's module

sick birch
#

Then you should do os.environ.get("os")

vale wing
#

That kills the point lol

sick birch
#

Indeed

vale wing
#

You access token by name of environment variable, not by token itself

hallow kernel
gray junco
#

Guys

#

How do i make the options appear? Im on py-cord btw

#

Slash cmd

buoyant quail
buoyant quail
#

Show how you are using it

gray junco
#

Oh i use autocomplete

#

Is it wrong

buoyant quail
#

It's not wrong, just a different thing

Choices are static, autocomplete are dynamic and they update each time you type something

gray junco
#

Why isnt it loading though

#

Imma use choices im done with autocomplete

buoyant quail
#

But yeah, you have just a static list so choices would be better

gray junco
#

Ty

left dew
#

in a ticket bot, is sending messages in a forum or normal channels better? and if so why

twilit grotto
left dew
twilit grotto
left dew
#

oh okay

mighty pilot
#

Probably just because forum channels don't clog up your channel list

left dew
#

does anyone have any docs on how to create threads with a bot?

buoyant quail
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.

New in version 2.0.
tepid dagger
buoyant quail
#

Because it takes only keyword args

#

!e

def f(*, x): ...


f(123)
unkempt canyonBOT
#

@buoyant quail :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     f(123)
004 | TypeError: f() takes 0 positional arguments but 1 was given
tepid dagger
#

so how does it work

#

as in how do i fix it

buoyant quail
#

!e

def f(*, x): ...

f(x=123)
unkempt canyonBOT
#

@buoyant quail :warning: Your 3.11 eval job has completed with return code 0.

[No output]
buoyant quail
#

Pass them as argument_name=value

tepid dagger
#

so like
embed.set_thumbnail(*,avatar)?

naive briar
#

No

tepid dagger
#

then what

#

url = avatar?

buoyant quail
#

Yes
(But avatar should be the link and not the Asset object as you have it now)

tepid dagger
#

then how do i make avatar a link

#

if it want it to be the user’s. avatar

buoyant quail
#

Look in the methods of the Asset

tepid dagger
#

so

#

avatar.url?

buoyant quail
#

yes

real oriole
#

wait

#

idk how to fix it

vale wing
#

When you fix something it works (unless you fix it in a wrong way)

real oriole
#

Im gonna fix it in a wring way

#

LO

#

what should i change ti make it a good way

vale wing
#

What's your python experience

real oriole
#

its literally the first

#

bot

naive briar
#

The first bot in the history of Discord bots!?

real oriole
vale wing
#

If it's your first python project I recommend finding a spoonfeeder getting more python knowledge first

real oriole
#

can u js tell me what to replace and what to replace it to now?

#

pweaseee

vale wing
#

That's why I said finding a spoonfeeder

#

I am not one ☺️

real oriole
#

oh.

#

di you know how to be one

#

(:

vale wing
#

Ofc it's easy

#

Just give code and spend lots of time figuring out issue of the beginner

real oriole
#

sinceu seem a good scripter tell me what to do to make it run now

naive briar
#

That sounds like a demand

real oriole
#

what does demand mean

turbid condor
naive briar
#

They told you hours ago

real oriole
#

oh lo

#

i was in school

#

does bot.client(‘’) work

turbid condor
#

nope

#

try to understand what Exenifix said

real oriole
#

ok

#

id rather be a noob than opening a book ti read or leadn that

#

lol

turbid condor
#

welp he didn't right anything in an alien language that's the most basic thing he's telling

#

you should at least know what's a variable

real oriole
#

ok

mighty pilot
#

If you're not willing to learn some basic knowledge it's going to be difficult to find someone to help you

#

Yea if you don't know the simple terms how are you going to know what they're telling you to fix lol

#

Yup

#

After running a discord server for a while I've learned nobody knows how to read anyways

nova vessel
naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

left dew
#

how do i set permissions/overwrites in a thread?

turbid condor
#

The same way you for a channel?

#

I'm not too sure tho

left dew
#

yes

tribal sleet
#

hellos sirs and female sirs

#

how i can execute a command when someone mentions the bot but there is also cooldown on the command and it should also work perfectly fine

buoyant quail
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix) attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
buoyant quail
#

The cooldown stays the same from prefix commands

tribal sleet
#

how it will know the comand to be executed

buoyant quail
#

same as with just prefix

@mybot hello
will execute hello

tribal sleet
#

hmm

#

can i post code

turbid condor
#

Yeah sure go ahead

#

Just remove any sensitive info from it if any

tribal sleet
#

@bot.command()
@commands.cooldown(1, 7200, commands.BucketType.user)
async def active(ctx):
  roles=ctx.author.roles
  print(roles)
  perms = discord.AllowedMentions(roles=True)
  role = discord.utils.get(ctx.guild.roles, id=1097188358322671616)
  for i in roles:
    print(i.id)
    if i.id==role.id:
      await ctx.send(role.mention, allowed_mentions=perms)
@bot.event 
async def on_message(message):
  if message.author==bot.user:
    return
  if bot.user in message.mentions:
    bot.invoke(active)


#

how i can invoke the active command wit its cooldown working

turbid condor
#

Wdym in above scenario the cool down is by user

buoyant quail
#

Invoke takes context, not command
Get message context and set ctx.command attribute to active, then use invoke with it. maybe this will be enough. I am not sure tho

tribal sleet
#

hmm

#

i try

hallow kernel
#

Can i make ability to bot to update/add/remove its commands without restarting it?

buoyant quail
#

Bot has add_command and remove_command methods

#

If you want to change code in them, loading code from the same file in already running script would be not really easy (if you don't have some cool code structure so you will need just to reimport these functions for example), you can use extensions and reload only one extension

dusk dagger
gray junco
#

Guys can someone provide a doc for a command that if you say !hello
It will send 2 messages that have a pause in between and the second message replies to the 1st

#

Nvm guys i found it

rough shuttle
#

``@tree.command(name = "poll", description = "make a poll!", guild=discord.Object(id=1136519406508326962))
@app_commands.describe(topic = "write the topic")
@app_commands.describe(o1 = "write no 1 poll")
@app_commands.describe(o2 = "write no 2 poll")
@app_commands.describe(o3 = "write no 3 poll")
@app_commands.describe(o4 = "write no 4 poll")

async def poll(interaction: discord.Interaction, topic: str, o1: str, o2: str, o3: str, o4: str,):
user = interaction.user
emojis2 = ["1️⃣", "2️⃣"]
emojis3 = ["1️⃣", "2️⃣", "3️⃣"]
emojis4 = ["1️⃣", "2️⃣", "3️⃣", "4️⃣"]
embed = discord.Embed(title=None, description=None)
if o3.lower() == "n/a":
embed = discord.Embed(title=topic, description=f"""

  1. {o1}
  2. {o2}""", color=discord.Color.purple())
    if o4.lower() == "n/a":
    embed = discord.Embed(title=topic, description=f"""
  3. {o1}
  4. {o2}
  5. {o3}""", color=discord.Color.purple())
    if o3.lower() == "n/a" and o4.lower() == "n/a":
    embed = discord.Embed(title=topic, description=f"""
  6. {o1}
  7. {o2}""", color=discord.Color.purple())
    embed = discord.Embed(title=topic, description=f"""
  8. {o1}
  9. {o2}
  10. {o3}
  11. {o4}""", color=discord.Color.purple())
    embed.set_footer(text=f"Action by {user.name} ({user.id})")
    em = await interaction.response.send_message(embed=embed)
    if o1 and o2 is not None:
    for emoji in emojis2:
    await interaction.user.add_reaction(emoji)``
#

the last line shows an error

#

pls help

slate swan
#

are we supposed to guess what error it shows?

rough shuttle
# slate swan are we supposed to guess what error it shows?

Traceback (most recent call last):
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 63, in poll
await interaction.user.add_reaction(emoji)
AttributeError: 'Member' object has no attribute 'add_reaction'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'Member' object has no attribute 'add_reaction'

#

forgot about it sry

slate swan
#

so .add_reaction is method for Message

#

you are doing it on Member object

#

!d discord.Message.add_reaction

unkempt canyonBOT
#

await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
rough shuttle
#

oh tysm bro

rough shuttle
slate swan
naive briar
#

Nothing will, if you still try to add a reaction to a user for some reason

rough shuttle
slate swan
#

.add_reaction is a Message method

#

its not a function

#

nor it takes 2 arguments

slate swan
rough shuttle
#

oh okay

slate swan
#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

sick birch
#

You can simply use the REST API for that

dusk dagger
#

This is the best free way

gray junco
#

Can anyone help me

#

Btw its pycord

dusk dagger
gray junco
#

btw its replying to a message

#

not a trigger

dusk dagger
#

A followup is normally best for interactions

gray junco
#

Do you have a doc or example for it

dusk dagger
#

Here's the docs for it, I've never used pycord so I'm not too sure if it's the same as dpy

#

What message are you trying to reply to tho?

#

If it's completely separate from the interaction you will need to get the message object, either by fetching it, or you could also get the partial message if it's cached.

gray junco
slate swan
#

https://discord.com/api/v9/channels/{channel_id}/messages

payload = content : "message"```
dusk dagger
dusk dagger
#

So prefix command?

gray junco
#

No

#

One sec

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

dusk dagger
#

Show me the code for this

#

Pycord is a little strange

gray junco
dusk dagger
#

It looks like a prefix command, is it not?

gray junco
#

Its prefix but supposed to be

#

slash cmd

dusk dagger
#

I suggest you don't use ChatGPT, it's outdated and you won't learn anything from it

gray junco
#

I just want to fix the error with the reply

dusk dagger
#

Yeah, I don't understand how ctx is a interaction object tho

#

Are you sure this is pycord?

gray junco
#

Yea its just async def dumbo(
ctx: discord.ApplicationContext
):

dusk dagger
#

It was a joke lol, I thought it would be somewhat obvious

dusk dagger
gray junco
dusk dagger
#

Run this to get a clean install of discord.py

import os
import sys

py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands"

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
gray junco
dusk dagger
gray junco
#

Its package tab of replit

dusk dagger
#

Oh, don't use replit to run or host your bot. It's not made for what you're trying to do, and it can cause issues that are purely based off replit.

#

Use a real IDE like vs code

gray junco
dusk dagger
#

Coding on mobile

gray junco
#

Ikr im ruining my code on mobile kinda

dusk dagger
#

it should work with dpy, you will just need to enable the message content intent

candid steeple
#

Anyone can help me with text recognition from image

dusk dagger
dusk dagger
slate swan
#

hi after trying this out of boredom, im getting an error and im confused rn

import requests

channel_id = input("Channel ID: ")
r = f"https://discord.com/api/v9/channels/{channel_id}/messages"
headers = {"authorization" : "pretend this is token"}

while True:
    message = input("Message: ")
    res = requests.post(url=r, headers=headers, data={"content" : message})
    if res.status_code == 200:
        print("successfully sent")
    else:
        print(res.content)```

bot has permissions and access to the channel
dusk dagger
#

If you're using Intents.default() disabling presences is redundant because default doesn't enable any privileged intents

slate swan
#

401 issue

#

it isnt gpt lol

dusk dagger
slate swan
#

oh

buoyant quail
#

It's raw api + input so it doesn't really matters

buoyant quail
dusk dagger
gray junco
#

Guys is there any example of a slash command and the slash command replies with a normal message? Ctx kinda doesnt work for me 😦

meager rock
sick birch
#

Also it has to be Authorization iirc

#

Note capital A

meager rock
#

i dont remember if it's case sensitive or not but going with convention the first char needs to be uppercase

buoyant quail
#

it's not case sensitive actually

buoyant quail
unkempt canyonBOT
buoyant quail
#

webhook for normal messages
as i remember works only after replying, but maybe not

#

or just take the channel

#

!d discord.Interaction.channel

unkempt canyonBOT
gray junco
#

Can you tell me please or send a example

buoyant quail
#

It has send method

#
async def some_command(interaction):
    await interaction.response.send_message("response")
    await interaction.followup.send("normal message")
upbeat mason
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="-", intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')

# KEEP THIS
bot.remove_command("help")
# KEEP THIS

@bot.command()
async def say(ctx, *text):
    await ctx.send(' '.join(text))  # Join the text with spaces

bot.run("token")

someone tell me why my bot does nothing when i run the say command 😭

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

buoyant quail
#

Prefix commands can't run without message content intent

#

you should also get a warning about it when you run it

upbeat mason
#

anyways thanks for the help

buoyant quail
upbeat mason
#

oh crap

#

i didnt see that

#

thought it was just part of the loading up stuff

buoyant quail
#

: )

gray junco
#

@buoyant quail you are a lifesaver

#

You deserve to get a role here ngl none helped me better than you

slate swan
#

and authorization didnt need to be capitalised

#

so any api request that i can see using the network tab, i can recreate by adding Bot to the auth header?

meager rock
drifting arrow
#

what would cause this?

#

do I need to update my discordpy? ;-;

quick brook
drifting arrow
quick brook
drifting arrow
#

lemme get it

drifting arrow
quick brook
drifting arrow
#

I'll upgrade now anyway

quick brook
#

ok

drifting arrow
#

figured it out

#

friend decided to move his API endpoints without letting me know -.-

slate swan
#

hello guys, i've been wanting to create a larger bot for a while now

#

but my only question is: what's the best way to sync a bot with a database?

#

i want to use mysql

#

my questions are stuff like: do i need just oen curosr active at all time? do i have a loop that makes sure the cursor is alive, do i need a queue for writing/reading data from the database?

quick brook
quick brook
#

TL;DR: MySQL is a bad database. Don't use it unless you have literally no other option.

Why shouldn't I use MySQL?

  • MySQL has no transactional DDL. This means that if you fuck up creating a table in the middle of a migration, you cannot rollback easily.
  • MySQL has a lot of security issues. New zero-day vulnerabilities are found regularly.
  • MySQL is owned by Oracle.
  • MySQL is slow. It beats Postgres etc at some things, but once you move beyond basic queries it begins to slog.
  • MySQL disconnects you randomly. Unless you setup your connection specially, it will break regularly.
  • MySQL allows all kinds of insane data to be inserted. '0000-00-00' is valid in MySQL.
  • MySQL is not ANSI compliant. You have to turn it on; even then it isn't fully compliant.
  • MySQL has no feature advantage over other databases; PostgreSQL has many more useful features (such as RETURNs).

There is no reason to use MySQL over PostgreSQL, or even sqlite3. See also:
https://blog.ionelmc.ro/2014/12/28/terrible-choices-mysql/
https://grimoire.ca/mysql/choose-something-else

slate swan
#

oh isee

#

connection pool is like available connections i can use, and when no connection is available i just wait for a new one to be available right?

quick brook
#

If you are looking for saving data then have a look at postgres.
PostgreSQL(https://www.postgresql.org/) is one of the best relational databases which is most programmers' first preference. We call it Postgres because why not?
The python driver, asyncpg(https://magicstack.github.io/asyncpg/current/), provides asynchronous support for Postgres!
If you have prior experience with SQL then you can easily switch to Postgres. If you don't then you can take this interactive tutorial at https://sqlbolt.com
Have a look at this Example Code as well to get a quick start: https://gist.github.com/jegfish/cfc7b22e72426f5ced6f87caa6920fd6

slate swan
#

its first time i see someone saying mysql is bad database

quick brook
slate swan
#

random disconnects cause of mysql or cause of the python library

buoyant quail
#

i was getting a lot of connection is closed for no reason

quick brook
quick brook
#

I've used PostgreSQL for 2 years and never had that happen to me

slate swan
#

yes postgres is better than mysql but i wouldnt say that you shouldnt use mysql casue of that

slate swan
slate swan
#

isn't a connection pool basically making psycopg asynchronous?

slate swan
quick brook
#

Plus 3.89x faster compared to psycopg3

quick brook
#

Asyncpg is also apparently 8.2x faster than node-pg

#

Based off of geometric means

mighty pilot
#

Isn't mariadb basically the same as mysql? I've been using that for over a year with no issues, just make sure you set the connection timeout to a value reasonable for your application

quick brook
#

Mariadb was forked bc MySQL basically got owned by Oracle

mighty pilot
#

Ah I see

quick brook
#

Mariadb strives to maintain compatibility with mysql but I haven't seen a good maintained mariadb driver out there that can compare to asyncpg

mighty pilot
#

Idkchu I use the one in their documents. Pretty straightforward. It was recommended to me by a friend that gets paid to do IT and I'm just a hobbyist so anything used in commercial applications is probably good enough for me

quick brook
#

Ah ok

mighty pilot
#

I just always thought it was a more updated mysql, because that's how it was described to me

quick brook
#

it is actually

nova vessel
dusty marsh
#

Would anyone here be able to share how they modeled their database for their discord bot, I have a few ideas but not sure which is the right approach

mighty pilot
#

Depends on what you're doing. I have a level bot that stores info in a table which the keys are server ID and user ID then I just have their points. Seperate table for specific server info like roles assigned at specific levels and level up difficulty and a bunch of other parameters associated with it

dusty marsh
mighty pilot
#

My original layout had the guild ID as the table names, but then I wanted to change some functionality so I made it all one table for user points info and a seperate table for server specific info with the guild ID as key and a new column for each piece of info stored for that guild

#

So 2 tables, one for points which stores guild ID (key) user ID (key) and points and a seperate table with guild ID (key) and a bunch of parameters associated with it

quick brook
quick brook
hushed galleon
slate swan
#

what software did u use for ur tables

#

thats really nice

hushed galleon
#

i just used the ERD feature of pgadmin because that was what i had on hand, the lines were quite finicky to edit

slate swan
#

gotcha

dusty marsh
#

so the user table

hushed galleon
#

but basically i normalized the various discord entities (users, channels, guilds, and messages) into their own tables for the benefit of clear relationships and cascading deletes
(for example if the starboard channel was deleted, i have the guild config table set to nullify the starboard channel ID, or if a message was deleted any stars recorded for that message would be deleted too)

dusty marsh
#

you dont store anything but the user

#

id

slate swan
#

all u need rly

#

unless u want other fields such as avatar url, username, display (all accessible through using the id)

hushed galleon
unkempt canyonBOT
#

src/thestarboard/database/api.py lines 149 to 152

await self.add_channel(channel_id, guild_id=guild_id)
await self.add_user(user_id)
await self.conn.execute(
    "INSERT INTO message (id, channel_id, user_id) VALUES ($1, $2, $3) "```
dusty marsh
hushed galleon
#

well really the main reason was i just wanted to make a normalized schema to see how it would go, but in practical usage you might find denormalizing your schema (e.g. no guild/user tables) easier to work with

#

in my schema i have it configured so if say, the bot gets removed from a guild, it can run a simple DELETE query on guild to make everything associated with that guild go away (config, channels, and messages)

quick brook
#

please just dont use on_ready

#

and also why do you need to close the bot afterwards?

#

and also please please do not spoonfeed code

#

generally you dont need to input the guild id, channel id, and message

#

i would recommend you read the examples first

final iron
#

How to get ratelimited 101

whole ocean
quick brook
quick brook
# whole ocean why

As noted in the docs, on_ready is also triggered multiple times, not just once

#

discord.py

#

examples can be found in the message linked above

#

you dont

whole ocean
quick brook
#

bruh why do you have the token to begin with

final iron
#

How do you have dynos token?

quick brook
#
  1. Before even attempting to create a discord bot, please learn python (!resources)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 - m pip install discord.py (windows)
    If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
    or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py

If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html

#

anyways

#

see this

#

np