#discord-bots

1 messages · Page 246 of 1

snow coral
#

UnboundLocalError: local variable 'sent_message' referenced before assignment

naive briar
#

No doubt about it

sick birch
snow coral
#

this worked, mine didnt

smoky sinew
#

replit and vscode use the same engine

smoky sinew
#

with

snow coral
north kiln
#

it is in a function you cannot access it directly

snow coral
#

oh

smoky sinew
#

it's not defined in the way you're thinking

#

don't use a command for this

snow coral
#

how should i do this then

north kiln
#

what are you trying to do

smoky sinew
#

you don't want to change it every 0.5 seconds first of all

#

you probably want to change it after the game is over, and also add a check for concurrency

snow coral
#

i need a new number every 0.5-1 second, because then i would need to rerun the code everytime, for a new number

smoky sinew
#

no you don't

north kiln
#

just pick the number when you run the command

snow coral
#

im trying to make something like this

smoky sinew
#

i'm typing

#
@commands.max_concurrency(1, per=commands.BucketType.user)
@bot.command(
    name="higherlower",
    description="Starts a new higher or lower game."
)
async def higher_lower(ctx: commands.Context) -> None:
    random_number = random.randint(1, 100)
    next_number = random.randint(1, 100)
    predictions = 0
    
    def check(reaction: discord.Reaction, user: discord.User) -> bool:
        return (
            user == ctx.author
            and reaction.message.channel == ctx.channel
            and str(reaction.emoji) in ("⬆️", "⬇️")
        )
    
    while True:
        message = await ctx.send(f"The number is {number}. Will the next number be higher or lower?")
        await message.add_reaction("⬆️")
        await message.add_reaction("⬇️")
        
        try:
            reaction, user = await bot.wait_for("reaction_add", check=check)
            if (
                (str(reaction.emoji) == "⬆️" and next_number > number)
                or (str(reaction.emoji) == "⬇️" and next_number < number)
            ):
                predictions += 1
                await reaction.message.add_reaction("✅")
            else:
                await reaction.message.add_reaction("❌")
                break
        except asyncio.TimeoutError:
            await ctx.send("You took too long! The game is over.")
            return

    await ctx.send(f"You lost! You were at {predictions} predictions.")
snow coral
#

holy

smoky sinew
#

this may not be correct but the general concept is to use a while loop inside the command

smoky sinew
#

well don't just copy and paste it

#

just take the concept

snow coral
#

okay

smoky sinew
#

max_concurrency basically ensures the user can only run one game at a time

#

wait_for waits for any event with a default time out of 180 seconds

unkempt mauve
#

https://paste.pythondiscord.com/kozosacasu

Issue: the bot does not responses to the elif not isinstance statement:( and I am not getting the errors either. Maybe the bot is still passing the number to the function even though its no longer an int

north kiln
#

it is not even sending str(result)?

naive briar
#

That's how it should be

#

You type hinted that the number parameter should be an int

unkempt mauve
#

but if the number is like 54a, it is no longer an int tho

naive briar
#

Then the bot will raise an error

unkempt mauve
#

it does not

naive briar
#

Do you have an error handler

unkempt mauve
#

I only have the discord.utils.setup_logging()

#

in main file

naive briar
#

No, an error handler

unkempt mauve
#

nope

naive briar
#

Show the code

unkempt mauve
#

which?

upbeat gust
#

and not using the help that you're being given at all on either

upbeat gust
unkempt mauve
#

and my issue is fixed already

idle lantern
#

anyone know a command for running a function that does something every 5 seconds in the background once called and ends after a certain time ?

unkempt mauve
#

lol what

upbeat gust
upbeat gust
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
unkempt mauve
upbeat gust
unkempt mauve
#

forgive ur fellow student

upbeat gust
unkempt mauve
#

they say "This menu is not yours" in ephemeral

idle lantern
idle lantern
# unkempt canyon

i tried the loop but how to make it stop automatically after a certain time?

unkempt mauve
#

input a count easy

upbeat gust
unkempt mauve
idle lantern
upbeat gust
unkempt mauve
upbeat gust
#

What?

unkempt mauve
#

damn u making me look like a dumb

upbeat gust
upbeat gust
unkempt mauve
#
  async def interaction_check(self, interaction: discord.Interaction):
    if interaction.user.id != self.author.id:
      try:
        await interaction.folowup.send('This command is not for you!')
      except discord.errors.NotFound:
        pass
      return False
    return True```
idle lantern
upbeat gust
#

there's nothing to follow up to

unkempt mauve
upbeat gust
#

No it's not

unkempt mauve
#

breh

#

oh nvm

#

I got it. nah I am dumb af

strong knoll
#

Can anybody repair me this line of code?:

        await interaction.guild.get_channel(channel_name).send_message(view=ChannelButtonView())
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

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 "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

can anyone help me understand intents?

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.

swift acorn
#
invites = {}

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="DM me to report a player!"))
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)!")
    except Exception as e:
        print(f"Sync Failed! {e}")

def has_perm(interaction : discord.Interaction):
    if interaction.user.id == 533692379777990656 or interaction.user.guild_permissions.administrator:
        return True
    else:
        return False
    for guild in bot.guilds:
        invites[guild.id] = await guild.invites()
    
@bot.event
async def on_invite_create(invite):
    if not invite.guild.id == 1039553876778561536:
        return
    
    invite_time = ""
    
    if invite.max_age == 0:
        invite_time = "Forever"
    if invite.max_age == 1800:
        invite_time = "30 Minutes"
    if invite.max_age == 3600:
        invite_time = "1 Hour"
    if invite.max_age == 21600:
        invite_time = "6 Hours"
    if invite.max_age == 43200:
        invite_time = "12 Hours"
    if invite.max_age == 86400:
        invite_time = "1 Day"
    if invite.max_age == 604800:
        invite_time = "7 Days"

    if invite.max_uses == 0:
        invite_uses = "Unlimited Uses"
    else:
        invite_uses = str(invite.max_uses)
    
    channel = invite.guild.get_channel(1111678175374741646)
    embed = discord.Embed(
        color=discord.Colour.yellow(),
        title="Invite Created",
        description=f"""
Created By: {invite.inviter.mention} ({invite.inviter} - {invite.inviter.id})
Valid For: {invite_time}
Uses: {invite_uses}
Invite Code: {invite.code}"""
    )
    await channel.send(embed=embed)
    for guild in bot.guilds:
        invites[guild.id] = await guild.invites()

def find_invite_by_code(invite_list, code):
    for inv in invite_list:
        if inv.code == code:
            return inv

@bot.event
async def on_member_join(member):
    if not member.guild.id == 1039553876778561536:
        return
    
    invites_before_join = invites[member.guild.id]
    invites_after_join = await member.guild.invites()
    channel = member.guild.get_channel(1111678175374741646)

    for invite in invites_before_join:
        if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
            embed = discord.Embed(
                        color=discord.Colour.green(),
                        title="Member Joined",
                        description=f"""
Member Joined: {member.mention} ({member} - {member.id})
Invite Code: {invite.code}
Inviter: {invite.inviter.mention} ({invite.inviter} - {invite.inviter.id})"""
            )
            await channel.send(embed=embed)

            invites[member.guild.id] = invites_after_join
            return
#

I am trying to make an invite tracker but it doesn't work for 1 time use invites since they expire and I get an error for trying to use, .uses on a NoneType object

vale wing
swift acorn
#

thanks for the suggestion!

#

But the invite issue is a headache I think it might just not be possible

vale wing
#

!d discord.Invite

unkempt canyonBOT
#

class discord.Invite```
Represents a Discord [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") or [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") invite.

Depending on the way this object was created, some of the attributes can have a value of `None`.

x == y Checks if two invites are equal.

x != y Checks if two invites are not equal.

hash(x) Returns the invite hash.

str(x) Returns the invite URL...
vale wing
#

Just saying .uses can be None

swift acorn
#

discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/creator_bot.py", line 124, in on_member_join
if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'uses'

vale wing
#

That so basically means invite is deleted after usage

#

You need a different approach - find the invite that is in old invites but is not in new ones

#

Can do that with sets

#
code = ({i.code for i in before_invites} - {i.code for i in after_invites}).pop()
#

Idk if you can put invites into sets but strings definitely

dry pelican
#

How do I make my bot detect a message sent in a channel?

#
@client.event
async def on_message(message):
    content = message.content
    print(content)

This is not working

slate swan
#

!intents

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
#

Enable the message content intent and then it will work

dry pelican
#

You mean this?

slate swan
#

I mean the code

dry pelican
#

Ohh thanks, i had typed intents.members = True

#

Thanks again!

#

Also, how do I make my bot work only in a specific server?

slate swan
#
  1. Make it private
  2. If you want, though unneeded once it's marked private, add an event handler for guild joins and make the bot leave the guild
dry pelican
#

hmm alright thanks!

slate swan
#

Just a toggle to activate in the developer portal

dry pelican
#

👍

dry pelican
#

How do I send an ephermal message?

north kiln
#

ephemeral=True in your send

naive briar
#

Only for interaction responses

#

And follow-ups

lean harbor
#

Any ideas for commands for both staff and members

slate swan
#

I Have a shop server and i have the command "$vouch". I wanna add a command like "$totalvouches" that shows how many people runned the command $vouch, how can i do it?

lean harbor
upbeat gust
slate swan
#

ill show u

strong knoll
slate swan
#
@bot.command()
async def vouch(ctx, *, suggestion):
  await ctx.channel.purge(limit=1)
  channel = discord.utils.get(ctx.guild.text_channels, name='✔〢vouchεs')
  suggest = discord.Embed(title=f'{ctx.author.name}', description=f'{suggestion}')
  sugg = await channel.send(embed=suggest)
  await sugg.add_reaction("❤️")
formal basin
#

checkforvideos.start()

#
  File "/home/runner/Nasheeds4u/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 123, in on_ready
    checkforvideos.start()
AttributeError: 'function' object has no attribute 'start'
#

i was doing an on_ready event

slate swan
#

show me the code

upbeat gust
slate swan
#

$vouch very good server

#

and later in this channel

upbeat gust
#

that's kinda- but ok

slate swan
upbeat gust
#

you should really store the count in a db unless you want to make tons of api calls every time you get the count (channel.history)

formal basin
# upbeat gust what's `checkforvideos`?
@tasks.loop(seconds=900)
async def checkforvideos():
  with open("youtubedata.json", "r") as f:
    data=json.load(f)
  

  print("Now Checking!")


  for youtube_channel in data:
    print(f"Now Checking For {data[youtube_channel]['channel_name']}")
    
    channel = f"https://www.youtube.com/channel/{youtube_channel}"

   
    html = requests.get(channel+"/videos").text

    try:
      latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
    except:
      continue

    if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:

      
      data[str(youtube_channel)]['latest_video_url'] = latest_video_url

      
      with open("youtubedata.json", "w") as f:
        json.dump(data, f)

      discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
      discord_channel_id = client.get_channel(int(discord_channel_id))

      msg = f"{data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or {data[str(youtube_channel)]['channel_name']} is Live Go Check It Out: {latest_video_url}"

      await discord_channel_id.send(msg)

      checkforvideos.start()


@checkforvideos.before_loop
async def checkforvideos():
  print('waiting... 2 ')
  await client.wait_until_ready()

@client.tree.command(name="add_youtube_notification", description="admin only")
@app_commands.default_permissions(administrator=True)
async def add_youtube_notification(interaction: discord.Interaction, channel_id: str, *, channel_name: str):
  with open("youtubedata.json", "r") as f:
    data = json.load(f)
  
  data[str(channel_id)]={}
  data[str(channel_id)]["channel_name"]=channel_name
  data[str(channel_id)]["latest_video_url"]="none"

 
  data[str(channel_id)]["notifying_discord_channel"]="1111972172303437935"

  with open("youtubedata.json", "w") as f:
    json.dump(data, f)

  await interaction.response.send_message("Added the YouTube Account Data!")```
slate swan
formal basin
#
@client.event
async def on_ready():
     await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name='Nasheeds4u'))
     print("bot online")
     try:
       synced = await client.tree.sync()
       print(f"synced {len(synced)} commands")
     except Exception as e:
          print(e)
     checkforvideos.start()```
upbeat gust
formal basin
upbeat gust
slate swan
#

oh yeah

#

how can i do it?

upbeat gust
#

do which one?

#

channel.history needs an api call for every 100 messages fyi

slate swan
#

the 2nd

#

i have no idea how to use db

upbeat gust
formal basin
slate swan
upbeat gust
upbeat gust
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.

Examples

Usage...
slate swan
#

use channel.history

upbeat gust
#

heres the docs then

formal basin
formal basin
#
async def setup_hook() -> None:
        checkforvideos.start()``` could I do this
formal basin
formal basin
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

formal basin
#

it doesnt work

naive briar
#

Doesn't explain anything

#

And you have two functions named checkforvideos. How is it possible to not notice that

upbeat gust
#

bruh

formal basin
formal basin
formal basin
twilit grotto
formal basin
#

nvm about it

harsh marsh
#

Hi, I created 2 buttons left arrow and right arrow and I want, once clicked it turn page but idk how to do. I found a tutorial on YouTube but it is with réactions and I want with buttons ^^

#

I don’t want the bot to respond to the interaction but just to change the page of the embed

slate swan
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
north kiln
young dagger
#

Why is this not working?

    # Get the channel object
    channel = client.get_channel(1067852667755429980)  # Replace with your desired channel ID

    # Fetch messages from the channel
    async for message in channel.history(limit=None):
        # Check if the message is not a pinned message and older than 2 minutes
        if not message.pinned and message.created_at < datetime.now() - timedelta(minutes=2):
            await message.delete()```
north kiln
#

what do you mean not working

young dagger
#
                         ^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'history'```
north kiln
#

is this in a command?

young dagger
#

No, I want to run it as a task:

class MyClient(commands.Bot):
    async def on_ready(self):
        print('Bot is ready!')
    async def setup_hook(self):
        auto_delete_messages.start()

@tasks.loop(seconds=10)  # Adjust the interval as needed
async def auto_delete_messages():
    # Get the channel object
    channel = client.get_channel(1067852667755429980)  # Replace with your desired channel ID

    # Fetch messages from the channel
    async for message in channel.history(limit=None):
        # Check if the message is not a pinned message and older than 2 minutes
        if not message.pinned and message.created_at < datetime.now() - timedelta(minutes=2):
            await message.delete()```
north kiln
#

is 1067852667755429980 a valid channel id?

young dagger
#

Yes

north kiln
#

well maybe the bot has not grabbed all guilds so it cannot find the channel

#

like the bot is not ready yet

#

they have different tzinfo I guess

#

also why do you need such task deleting messages every 2 minutes

#

obv but what's the purpose of it

snow coral
#

how can i make a command channel specific? (so the command only works in that one channel)

slate swan
#

ctx.channel.id or interaction.channel.id

#

It's mine error

#

@slate swan

turbid condor
#

U haven't added ctx in the async

slate swan
#

Hm

#

Added

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

@bot.command()
async def help(self, ctx):
    embed = discord.Embed(title="**__Celestial Help__**",description="My pefix is !\nUnder development", color=discord.Color.blue())
    embed.add_field(title="**Some catagory of my commands are**", description="![red_dot](https://cdn.discordapp.com/emojis/1111643807352623165.webp?size=128 "red_dot") Utility\n![red_dot](https://cdn.discordapp.com/emojis/1111643807352623165.webp?size=128 "red_dot") Moderation\n![red_dot](https://cdn.discordapp.com/emojis/1111643807352623165.webp?size=128 "red_dot") Fun\n![red_dot](https://cdn.discordapp.com/emojis/1111643807352623165.webp?size=128 "red_dot") Giveaway")
    await ctx.send(embed=embed)
#

There is no self in main commands

turbid condor
#

No need to use self this is not a cog

slate swan
#

Only in cogs

#

And don't use remove_command

#

Oh

slate swan
#

;-;

#

help_command=None in your bot constructor

turbid condor
#

Subclass it

slate swan
slate swan
#

Better practice than remove_command

#

Ok

turbid condor
slate swan
#

@slate swan hey in embed.add_field we can't use title ???

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
slate swan
#

As you can see, it's name and value

#

Oh ok

astral ether
#

hello anyone know, if it's possible to make this in discord.py ?

slate swan
#

Yes, it's called a modal

astral ether
slate swan
#

@slate swan hey can you tell me how to make this maybe last ping please

slate swan
#

How can I make it

formal basin
#
@client.tree.command(name="random-number", description="sends a random number choose a number e.g 1 10")
async def randomnumber(interaction: discord.Interaction, number1: int, number2: int):
  await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))
#
Traceback (most recent call last):
  File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 24, in randomnumber
    await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))
TypeError: InteractionResponse.send_message() takes from 1 to 2 positional arguments but 3 were given

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

Traceback (most recent call last):
  File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 856, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'random-number' raised an exception: TypeError: InteractionResponse.send_message() takes from 1 to 2 positional arguments but 3 were given```
north kiln
#

...

slate swan
#

What the 😂

formal basin
#

so im making a random number command where you chose the from number to number

astral ether
# slate swan How can I make it
class Select_catalogue(discord.ui.Select):

    def __init__(self):

        options=[
            discord.SelectOption(label="text",emoji="🌠",description="text"),
            discord.SelectOption(label="text2",emoji="🚀",description="text" + commandes_admin[1]),

            ]
        super().__init__(placeholder="Cliquez pour consulter les commandes disponible",max_values=1,min_values=1,options=options)

    async def callback(self, interaction: discord.Interaction, timestamp=None):
        if self.values[0] == "text":

            embed_test = discord.Embed(colour=None, color=random.choice(colors), title='Fonction de Bienvenue !', type='rich', description='test')
            await interaction.response.send_message(embed=embed_test ,ephemeral=True)
            
        elif self.values[0] == "text2":

            embed_test = discord.Embed(colour=None, color=random.choice(colors), title='commande', type='rich', description='test')
            await interaction.response.send_message(embed=embed_test ,ephemeral=True)
            


# Classe pour appellez le catalogue

class SelectView(discord.ui.View):
    def __init__(self, ctx):
        super().__init__()
        self.add_item(Select_catalogue(ctx))



view = SelectView(ctx)
await ctx.send(embed=embed, view=view)
north kiln
#

you aren't even setting the string correctly

slate swan
#

dont spoonfeed

astral ether
north kiln
#

read your code again

slate swan
formal basin
north kiln
#

yes

formal basin
#

ok

north kiln
#

how are you sending your messages

formal basin
slate swan
north kiln
#
await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))

you think this is correct?

formal basin
#

yes...

north kiln
#

this isn't print()

#

you can't just concat string like that

#

put it inside the f string

formal basin
slate swan
slate swan
formal basin
slate swan
formal basin
#

if i didnt put it in f string

slate swan
#

It will print

formal basin
#

no it cant

slate swan
#

Number1

formal basin
#

i dont have print in my code

slate swan
#

Huh send_message I mean 🗿

formal basin
#

oh

slate swan
slate swan
#

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

dry kelp
#

what is a _meta ?

#

Never heard of that

#

Here i am trying to create the model and once i try to add the author id to the ManyToManyField It won't work due to that error.
Using tortoise that should be the way to add an id to the models

buoyant quartz
#

anyone know why this constantly appearspy Ignoring exception in on_application_command_error Traceback (most recent call last): File "c:\path-to-file", line 490, in _run_event await coro(*args, **kwargs) File "c:\path-to-file", line 281, in on_application_command_error raise error File "c:\path-to-file", line 890, in invoke_callback_with_hooks await self(interaction, *args, **kwargs) File "c:\path-to-file", line 3402, in trivia await interaction.channel.send(file=file, embed=embed) File aiohttp.client_exceptions.ClientOSError: [Errno 1] [SSL: SSLV3_ALERT_BAD_RECORD_MAC] sslv3 alert bad record mac (_ssl.c:2578)

slate swan
#

hello someone fix this error ?

Traceback (most recent call last):
File "C:\Users\aress\OneDrive\Bureau\Selfbot\main.py", line 42, in <module>
bot = commands.Bot(command_prefix='.',self_bot=True)
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

slate swan
#

if i send you the main.py can you fix it ?

slate swan
#

!intents

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
#

wait go dm plz

sick birch
slate swan
slate swan
#

I think you're right though, self_bot is to indicate self bots iirc

vocal snow
vocal snow
#

because you haven't defined anything called ButtonView

snow coral
#

i keep getting
TypeError: expected token to be a str, received NoneType instead

twilit grotto
snow coral
#

i could generate a new tolen

twilit grotto
#

pritn it make sure it prints correctly

snow coral
#

token

weary birch
#

how can i make automatic message sent when i upload video/post to instagram i want it to sent to #instagram

smoky sinew
#

hi

smoky sinew
#

💀

#

stop making selfbots

weary birch
#

lmao ☠️

weary birch
#

thanks anyway

smoky sinew
#

actually doing a little research it looks like instagram shut down their feed api

smoky sinew
#

nobody uses reels

snow coral
marble wasp
#

how would one create instances for discord bots? so that people can use their own tokens for a discord bot to get their own branding on a bot?

snow coral
#

yeah

snow coral
smoky sinew
#

# adding reactions not what this does btw, this is just a check to make sure the reaction is correct

snow coral
#

lol

dry kelp
#

@smoky sinew I got a question

smoky sinew
#
  • you can use {user.mention} instead of <@{user_id}>
  • if member == None: should be if member is None: and name and pfp should be defined outside the if statement
  • for the leaderboard you need a database
  • minor nitpick - you don't need time or os, and you don't need reactions intent since you already have it included in n discord.Intents.default()

as for your actual question @snow coral

#

you can add a global check

smoky sinew
#
bot.add_check(lambda ctx: ctx.channel.id in ALLOWED_CHANNELS)
dry kelp
#

talking to me?

smoky sinew
#

or with a decorator: ```py
ALLOWED_CHANNELS = (1111885634336985178,)

@bot.check
def check_channel(ctx: commands.Context) -> bool:
return ctx.channel.id in ALLOWED_CHANNELS

snow coral
smoky sinew
#

with what

snow coral
#

TypeError: argument of type 'int' is not iterable

smoky sinew
#

(1111885634336985178**,**)

#

that makes it a tuple

#

() and (0,) are both tuples, (0) is a singleton

snow coral
#

oh

smoky sinew
#

(((0))) is still a singleton

snow coral
#

didnt think the comma was important

snow coral
#

like 2

#

instead of 1

smoky sinew
#

you just put another number in there

#

(0, 1)

snow coral
#

okay

snow coral
smoky sinew
#

cool

gilded oxide
#

does anyone wanna help or explain to me how to make antinuke command?

smoky sinew
#

just have a bunch of checks and a counter for each user

gilded oxide
#

well..

smoky sinew
#

ban them if they’re over a threshold

gilded oxide
#

but idk how

smoky sinew
#

events

west comet
#

@vocal snow

#

😒

#

Why u bn me

dry kelp
#

Why is it none? when is it being added to the database, and the return message for afk member when comes back works perfectly fine and it also gets removed from db

naive briar
#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
naive briar
dry kelp
fading marlin
#

if it's not found in cache, which is only populated if you've got the members intent enabled

dry kelp
#

all intents are enabled

fading marlin
#

get_member expects an ID, not a mention

dry kelp
#

well yeah ofc its an int field

#

there is an int, which is user id

fading marlin
#

you sure user_m isn't a string?

dry kelp
#

Ofc

fading marlin
#

what does get_or_create return?

golden portal
# dry kelp

User.get_or_create returns your model object and a bool, so your user_m is a model, use user_m.id

dry kelp
dry kelp
#

in the database is being added the int of the afk member

naive briar
#

That doesn't answer anything

dry kelp
#
    @Cog.listener()
    async def on_message(self, message: Message):
        if message.author.id == self.bot.application_id:
            return

        afk = await AfkModel.get_or_none(guild_id=message.guild.id)
        user, created = await User.get_or_create(id=message.author.id)

        if afk:
            if message.author != message.guild.owner:
                await message.author.edit(nick=message.author.name)

            async for item in afk.discord_id:
                if item.id == message.author.id:
                    await message.reply(
                        f"Welcome back {message.author.mention}! "
                        f"You went afk - {format_dt(afk.time, style='R')}"
                    )
                    await afk.discord_id.remove(user)

        if message.mentions:
            if afk:
                async for item in afk.discord_id:
                    if item.id == message.mentions[0].id:
                        member = message.guild.get_member(item)
                        await message.reply(
                            f"**{member.display_name}** is AFK because: `{afk.reason}` "
                            f"{format_dt(afk.time, style='R')}"
                        )
fading marlin
#

what

#

that doesn't answer anything either

dry kelp
#

Ok so look, in this part im also checking the message, which works perfectly fine

#

Only the message mentions are the problem

#

even if i pull the objects out of the discord_id which is the afk member list for that guild it would still return none

golden portal
dry kelp
#

wait

#

You are right

golden portal
#

i wouldnt use orm without knowing fundamental tbh

dry kelp
#

I just assumed it

golden portal
#

plus orm is always slower

dry kelp
#

Is it?

#

What would u recommend? But i honestly prefer tortoise orm

golden portal
#

i would just use a db driver like asyncpg and do raw sql from that, last time i used tortoise orm is when it is provided by the framework like django

dry kelp
#

So i will just continue using tortoise for now

golden portal
#

sure

shrewd apex
#

altho i don't specifically use orm i use asyncpg for the sql queries and attrs/dataclasses to validate models

dry kelp
#

There's 1 more issue i forgot about, adding time and reason per user, not per guild 😂

golden portal
# shrewd apex definitely has more pros than cons to it

only pros i can think of is it being faster to develop an application with friendly interface assuming you already have the skill and good core, but the cons are still huge, slower runtime, not skill transferable to other languages. not knowing the fundamental of sql would be an issue for the user not knowing how would they optimize a query. everytime you are face with a new orm you are force to relearn the quark of that orm, it gets annoying

shrewd apex
shrewd apex
dry kelp
#

I currently have no logic to do this, but i will surely find out tomorrow

shrewd apex
#

good luck 👍

dry kelp
#

Will need it pithink

#

Do you guys think that should i rewrite the entire code making user id primary, which means more tables but i wont need to sort all the schema out i just have to add the guilds to the user id which would be a lot easier

#

what do you guys think? @shrewd apex @golden portal

#

which is even more nice i can add timestamp on creation

#

and it wont cause any issues

golden portal
dry kelp
golden portal
#

so i mean, if you're talking about AFK table to store the afk states, depending on how you want it to behave for example, if you want it to apply to just a specific guild, make both user id and guild id a primary key, so its a composite key, if you want the afk to apply to all guilds, make only user id a primary key

shrewd apex
#

^^

smoky sinew
#
CREATE TABLE IF NOT EXISTS afk_members (
    user_id BIGINT NOT NULL,
    guild_id BIGINT NOT NULL,
    since TIMESTAMP NOT NULL DEFAULT (NOW() AT TIME ZONE 'utc'),
    reason TEXT,
    PRIMARY KEY (user_id, guild_id)
);
shrewd apex
smoky sinew
#

that should be a frontend thing

shrewd apex
#

why not? it can be done here also

smoky sinew
#

what if they want multiple languages for example, then you would have to update all rows from "no reason provided" to null

shrewd apex
#

if they want multiple languages let the user just enter in their own language

smoky sinew
gilded oxide
#
    @commands.group(invoke_without_command=True)
    @commands.has_permissions(manage_roles=True)
    async def role(self, ctx, user: discord.Member, *, role: discord.Role):
        if role in user.roles:
            await user.remove_roles(role)
        else:
            await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, user: discord.Member, *, role: discord.Role):
        await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
        await user.remove_roles(role)``` how do I add more of these commands?
smoky sinew
#

user: discord.Member

#

btw on commands like these you need a guild_only check

#

though i think has_permissions takes care of that

slate swan
#

If someone blocked you, they don't see your messages

#

Unless they explicitly look at the message, which then misses the point of having them blocked

upbeat gust
#

🤨

vocal snow
upbeat gust
#

hey mudkip, I don't know if you remember me but can you unblock me in dms and we need to talk.

north kiln
#

do slash commands have ids attached to them?

#

like message ids and guild ids

slate swan
#

yup

marble wasp
#

When creating ticket transcripts, i currently get them uploaded to github and then have to manually download them and open the .html

is there a way i can get these to auto upload to somewhere like tickettool so i do not have to download and rather be able to just open in the internet?

north kiln
slate swan
#

!d discord.app_commands.CommandTree.fetch_commands

unkempt canyonBOT
#

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

Fetches the application’s current commands.

If no guild is passed then global commands are fetched, otherwise the guild’s commands are fetched instead.

Note

This includes context menu commands.
slate swan
#

The returned objects have an id attribute

#

For example

cmds = await bot.tree.fetch_commands()
print(cmds) # List of AppCommand objects
naive briar
#

!d discord.app_commands.AppCommand.id

unkempt canyonBOT
tough lance
#
0|hak  | Ignoring exception in on_application_command
0|hak  | Traceback (most recent call last):
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 700, in _run_event0|hak  |     await coro(*args, **kwargs)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1361, in on_application_command
0|hak  |     await self.process_application_commands(interaction)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1353, in process_application_commands
0|hak  |     await app_command.invoke(interaction)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/slash_core.py", line 719, in invoke
0|hak  |     await self.prepare(inter)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 324, in prepare
0|hak  |     if not await self.can_run(inter):
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 630, in can_run
0|hak  |     ret = await maybe_coroutine(local_check, inter)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/disnake/utils.py", line 599, in maybe_coroutine
0|hak  |     return await value
0|hak  |   File "/root/Hak/cogs/cards.py", line 20, in cog_slash_command_check
0|hak  |     r = await self.bot.get_profile(inter.author.id)
0|hak  |   File "/root/Hak/db.py", line 178, in get_profile
0|hak  |     async with self.curr.acquire() as conn:
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 998, in __aenter__
0|hak  |     self.connection = await self.pool._acquire(self.timeout)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 838, in _acquire
0|hak  |     return await _acquire_impl()
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 823, in _acquire_impl
0|hak  |     proxy = await ch.acquire()  # type: PoolConnectionProxy
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 137, in acquire
0|hak  |     await self.connect()
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 129, in connect
0|hak  |     self._con = await self._pool._get_new_connection()
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 521, in _get_new_connection
0|hak  |     con = await connect_utils._connect_addr(
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/connect_utils.py", line 768, in _connect_addr
0|hak  |     return await __connect_addr(params, timeout, False, *args)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/connect_utils.py", line 825, in __connect_addr
0|hak  |     tr, pr = await compat.wait_for(connector, timeout=timeout)
0|hak  |   File "/usr/local/lib/python3.10/dist-packages/asyncpg/compat.py", line 56, in wait_for
0|hak  |     return await asyncio.wait_for(fut, timeout)
0|hak  |   File "/usr/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
0|hak  |     return fut.result()
0|hak  |   File "/usr/lib/python3.10/asyncio/unix_events.py", line 254, in create_unix_connection
0|hak  |     await self.sock_connect(sock, path)
0|hak  |   File "/usr/lib/python3.10/asyncio/selector_events.py", line 500, in sock_connect
0|hak  |     return await fut
0|hak  |   File "/usr/lib/python3.10/asyncio/selector_events.py", line 505, in _sock_connect
0|hak  |     sock.connect(address)
0|hak  | FileNotFoundError: [Errno 2] No such file or directory
```I start getting this error after a few hours of uptime on my bot. I have no idea why this is happening and the bot won't respond to any commands after this. A temporary fix is just to restart the entire vps.
marble wasp
#

When creating ticket transcripts, i currently get them uploaded to github and then have to manually download them and open the .html

is there a way i can get these to auto upload to somewhere like tickettool so i do not have to download and rather be able to just open in the internet?

slate swan
tough lance
#

It does work for sometime.

#

But stops working after a while

upbeat otter
#

how do you convert a File/Attachment object to bytes 💀

formal basin
#
@client.tree.command(name="random-number-button", description="Sends a button that when clicked sends a random from number1 to number2")
async def randomnumberbutton(interaction: discord.Interaction, number1: int, number2: int):
  try:
      button = Button(label=f"Random number from {number1} to {number2}", style=discord.ButtonStyle.primary)
      channel = client.get_channel(1112053260879147130)
     
     
  
  
      async def button_callback(interaction):
       await interaction.response.send_message(random.randint(number1, number2))
       await channel.send(f"random number button clicked by {interaction.user}")   
    

       button.callback = button_callback
  
       view = View()
       view.add_item(button)
       await interaction.response.send_message("Click the button to get a random number from 1 to 20", view=view)
       await channel.send(f"random-number-1-to-20-buttons command used by {interaction.user}")
  except:
      channel2 = client.get_channel(1112053260879147130)
      await interaction.response.send_message("error: The number1 needs to be bigger than number2")
      await channel2.send(f"random-number-button command used by {interaction.user} but an error occured")
formal basin
#

no error

naive briar
#

Did you try to look at your own code

formal basin
naive briar
#

Then you should already see what's wrong

formal basin
naive briar
#

Your code responsible for responding is inside the button callback

#

And it will never be executed

whole shoal
#

How to add that add to server button on a bot

marble wasp
#
@client.hybrid_command(name="logging", description="Setup your logging channels")
async def logging(ctx, log_type, channel: discord.TextChannel):
    log_type.options= {
    "role_update",
    "message deleted",
    "message edited",
    "Moderation Actions"
    }
    valid_log_types = ["role_updates", "message_deletes", "message_edits", "mod_actions"]
    if log_type not in valid_log_types:
        await ctx.send("Invalid log type. Valid log types are: role_updates, message_deletes, message_edits, mod_actions.")
        return

    set_log_channel(ctx.guild.id, log_type, channel.id)
    await ctx.send(f"{log_type} logs will be sent to {channel.mention}")

why can i not get options when i do /logging?

meager chasm
#

You're setting .options attribute of a string in the command callback

marble wasp
#

ive not read it im asking for someone else, cuz hes banned from the cord

meager chasm
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
shrewd apex
#

it will raise an AttributeError

meager chasm
meager chasm
astral ether
#

hello, anyone know how to use database with discord.py ?

gilded oxide
# upbeat gust just put more..?
    @commands.group(invoke_without_command=True)
    @commands.has_permissions(manage_roles=True)
    async def role(self, ctx, user: discord.Member, *, role: discord.Role):
        if role in user.roles:
            await user.remove_roles(role)
        else:
            await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, user: discord.Member, *, role: discord.Role):
        await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
        await user.remove_roles(role)
    
    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def create(self, ctx, user: discord.Member, *, role: discord.Role):
        await user.create_roles(role)``` like that? because in the create command it is white at create_roles instead of being colored
astral ether
#

well me for my personal bots I use files to save my data but I would like to switch to a database for the bots which are on a lot of servers, but I have never used a database

vocal snow
gilded oxide
# vocal snow What's your question?

is this correct? because when its in role add or remove it is colored at the user.remove_roles(role) and user.add_roles(role) but it is white at user.create_roles(role)

vocal snow
#

So maybe create_roles isn't a valid method?

#

Did you check the documentation to see if it exists?

gilded oxide
#

no my friend helped me make these

#

could u send the doc

vocal snow
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
gilded oxide
#

yea its not there

#

so what should I use instead

vocal snow
#

What is user.create_roles even supposed to do

#

You can't create roles for specific members in discord

#

You create roles specific to servers (guilds)

#

!d discord.Guild.create_role

unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.

All fields are optional.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.

New in version 2.0: The `display_icon` keyword-only parameter was added...
gilded oxide
vocal snow
#

no

#

I would really recommend learning python before this

gilded oxide
#

im js confused on what to do ik how to code it now but like

#

what should the primary code to set it up look like?

vocal snow
#

get a Guild object (eg, ctx.guild); call it's create_role method

dry kelp
#
class AfkModel(Model):
    """AFK Model."""

    discord_id: int = BigIntField(pk=True)
    guild_id: ManyToManyRelation[Guild] = ManyToManyField(
        "Bot.Guild", related_name="afk_guilds"
    )
    reason = TextField(null=False)
    time = DatetimeField(auto_now=True)
#
    @slash_command()
    async def afk(
        self,
        inter: disnake.ApplicationCommandInteraction,
        reason: str = Param(default=Ellipsis, max_length=100),
    ):
        """
        Set your status to AFK.

        Parameters
        ----------
        reason: Reason for going AFK.
        """

        if "[AFK]" in inter.author.display_name:
            await inter.send("AFK detected in name, aborting...")
            return

        await inter.response.defer()

        afk = await AfkModel.get_or_none(discord_id=inter.author.id)
        guild, created = await Guild.get_or_create(id=inter.guild.id)

        if afk:
            await afk.guild_id.add(guild)
            await AfkModel.update_or_create(reason=reason)
        else:
            afk_create = await AfkModel.create(
                discord_id=inter.author.id, reason=reason
            )
            await afk_create.guild_id.add(guild)

        if inter.author != inter.guild.owner:
            await inter.author.edit(nick=f"[AFK]{inter.author.display_name}")
        await inter.send(
            f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
        )
#
    @Cog.listener()
    async def on_message(self, message: Message):
        if message.author.id == self.bot.application_id:
            return

        afk = await AfkModel.get_or_none(discord_id=message.author.id)
        guild, created = await Guild.get_or_create(id=message.guild.id)

        if afk:
            if message.author != message.guild.owner:
                await message.author.edit(nick=message.author.name)

            async for item in afk.guild_id:
                if item.id == message.guild.id:
                    await message.reply(
                        f"Welcome back {message.author.mention}! "
                        f"You went afk - {format_dt(afk.time, style='R')}"
                    )
                    await afk.guild_id.remove(guild)

            if message.mentions:
                user = await AfkModel.get_or_none(discord_id=message.mentions[0].id)
                member = message.guild.get_member(user.id)
                await message.reply(
                    f"**{member.display_name}** is AFK because: `{afk.reason}` "
                    f"{format_dt(afk.time, style='R')}"
                )
#

This afk command works almost fine, the only issue that im having is that once a user goes afk in a certain guild, then goes to another guild afk the reason and time will be updated to the "new afk guild" and i don't want that, reason and time should be per guild

#

anyone have any ideas of how could i make reason and time per guild?

dry kelp
vocal snow
#

you need a composite primary key of (discord_id, guild_id), and you'll need to pass both of those when fetching from the database

dry kelp
#

Here's the thing, using this orm i don't know how to have multiple primary keys

#

i actually tried looking for that

#

in the tortoise orm docs

vocal snow
#

i see

#

well you can still fetch the model with both values

#

afk = await AfkModel.get_or_none(discord_id=message.author.id) doesn't mention the guild id... you need to add that so it only retrieves the model for the current guild

dry kelp
#

Yeah i told u my only problem because basically the schema now is like this:

{afkuser:id, afkinguilds:[1,2,3..], reason:reason, time:time}
vocal snow
#

are you actually storing a list?

dry kelp
#

Didn't u see my models?

#

Yes, I have to

vocal snow
#

I did, and you have a Many to Many relation, that's not the same as storing a list

dry kelp
#

ManyToManyRelation is actually that, storing a list of guild ids

vocal snow
#

not at all, there are two main tables and a third one that relates them

dry kelp
#

And let me tell you why, if i had made the models simple, having guild id as aprimary let's say, another user couldn't go afk right?

#

Because of duplicated key

#

And that's the reason why i've moved to mtm relations

#

So i can store multiple guild ids where the user can actually go afk

vocal snow
#

yes, but your database is not storing a list

#

there is a table for Afk users, a table for Guilds, and a table that relates them

#

even though you might be getting a list in python (thanks to the ORM)

vocal snow
#

that doesn't change my answer, you need to adjust your code so it will only retrieve the AfkModel that belongs to the current guild

dry kelp
#

Well yeah it is not a list, it's storing multiple fields of guilds id, was just telling u an example

dry kelp
#

But if you go in other guilds afk reason will be updated same as time

#

here is adding the new guild if the afk member id was already found

#

and by updating the model using update_or_create it will update the reason which shouldn't be doing that

#

and the time is automatically being updated thanks to the DatetimeField

#

so i don't need to store a str and whatever, just a painful thing

vocal snow
#

actually a m-m relation doesn't make sense here because one AfkModel can only belong to one guild

dry kelp
#

EXACTLY

#

now u got to my point

#

I need to make it global

vocal snow
#

Table AFK    Table Guild  

user_id      guild_id 
guild_id     guild_name
...          ...

``` it's as straightforward as this
#

And AFK primary key has to be composite

#

if your ORM doesnt support that then idk what you can do

dry kelp
#

Should be able to

#

I just don't know how to make it composite

#

Never had multiple pks But knowing how to do it would help a lot in the future

#

Also mind checking ur dms? I wanna show u an example

#

@vocal snow

shrewd apex
dry kelp
#

It works perfectly fine

bold trench
#

Hey, could someone help me write bot suggestions

dry kelp
smoky sinew
bold trench
#

That after writing the message, he deletes it, makes a message from the bot with the content written by the user and adds reactions

dry kelp
#

So someone to "suggest" something for your bot?

dry kelp
#

Who writes the message and who is "he"

bold trench
#

No look my message

#

New proposal: Tresc

#

And the message that the user wrote is deleted and the bot sends it with reactions

potent spear
#

embedded most likely

dry kelp
#

Oh, i could give u a code for that, i was using embed + buttons, it's just outdated, you would have to work on it

#

It's also connected to database, so in case bot goes offline you can still interact with the buttons

bold trench
#

Give me code bro

dry kelp
#

👍

smoky sinew
#

why

#

just write it yourself it's pretty simple

slate swan
worthy heart
#

quick question, how can I safely make a command named list

#

not so cool

#

as list is a type

bold trench
glad cradle
sick birch
worthy heart
#

yea

bold trench
#

Does anyone have command suggestions?

worthy heart
#

ideas?

smoky sinew
#

you just take an argument named feedback and then delete ctx.message

potent spear
worthy heart
#

it gets greyed out

potent spear
#

or list_

worthy heart
#

kinda scares me ngl

potent spear
#

it will eat you, true

worthy heart
#

I named it list_

dry kelp
#
[tool.poetry.scripts]
bot = "spooky.bot.__main__:exec"
web = 'helpers.web_run:dev'
web-prod = 'helpers.web_run:prod'
#
FROM python:3.11 as base
RUN     apt update
RUN     apt install -y python3-pip python3-wheel gcc
RUN     pip install    poetry
WORKDIR /app

COPY ./poetry.lock ./pyproject.toml /app/

RUN poetry config virtualenvs.create false
RUN poetry install

COPY . /app/

FROM base as web
EXPOSE 8000
CMD python3 ./helpers/wait_to_db.py && poetry run aerich init-db && poetry run web-prod

FROM base as bot
CMD python3 ./helpers/wait_to_db.py && poetry run aerich init-db && poetry run bot
vale wing
#

Pretty sure you need compose

slim salmon
#

hey so, i'm new to discord.py and i want to make a command that would search a channel for a certain message string and then return a value of of how many messages were found including that string. i'm not exactly sure how i could go about this so any help would be appreciated!

dry kelp
# vale wing Pretty sure you need compose

Actually no, i just texted someone that contributed to docker, They said it's well structured and it doesn't require any changes and that the warning shouldn't be affecting the bot

#

which in fact it doesn't affect the bot and it works properly

smoky sinew
slim salmon
#

ah, thanks!

#

i think i have somewhere to base it off of now,

slim salmon
#

this is what i have so far, it's going well but i'm not entirely sure how to actually count a specified word, i've tried a few things without avail, some explanation would be helpful, thanks!

slate swan
#

Also this is already a built-in feature on Discord, just letting you know

slim salmon
#

i know, just wanted to challenge myself and build it into a bot

smoky sinew
#

like you could be looping over millions of messages

#

and making a lot of api calls

#

also you want to define counter inside the command, and use += 1 instead of + 1

slim salmon
smoky sinew
#

cache messages in some kind of database

#

though you should ask for consent as storing messages is pretty invasive

slim salmon
#

yeah, currently just on a private testing server with only myself in it

potent spear
#

this can greatly reduce your API calls: you can basically "catch" every message in your on_message and count in that event instead
possible downside: if your bot goes offline, the messages won't be counted anymore

tired pine
#

Just made this https://hastebin.com/share/judosijoko.rust and I'm off to sleep, I'd like to wake up with a few ideas of slash commands or other thing to make

naive briar
#

lol

drifting arrow
smoky sinew
drifting arrow
#

Heh

#

Just bored. Gotta sit in car waiting for some old man to finish getting zapped .

#

:-; I could be home programming but nooo real life is like “go outside” and I’m like no there are bees

slate swan
#

Bees are nice

snow coral
#

how do i make my bot have a status

snow coral
#

why does my bot have its own help command that i never coded

#

and how do i get rid of it

#

cause i wanna make my own help command

naive briar
snow coral
#

i fixed it

smoky sinew
#

if you're extending the default one you can just override MinimalHelpCommand or HelpCommand otherwise just set help_command to None ```py
bot = commands.Bot(
...,
help_command=None
)

vale wing
# dry kelp Actually no, i just texted someone that contributed to docker, They said it's we...

Well I kinda do have concerns about that person knowing dockerfile well. First, as per dockerfile reference, you cannot have more than one CMD instruction in single Dockerfile. Second, multiple FROM statements indicate that you are doing multi-stage build. I highly doubt this is your case, as it's typically used in scenario where you first need to build an executable then to run it. From what I can see, you want to run a bot then concurrently run web. That's exactly what docker-compose is for.

The warning actually appears because of enabled logging I guess. I couldn't find any information regarding dev mode on disnake docs but heard it automatically reloads extensions on files change

#

Warning has nothing to do with docker but you definitely should look into compose

sturdy dragon
#

Hey guys just interested if any of you had preferences around cloud hosting ? If so who did you go with ? Thx

formal basin
#
async def kick(interaction: discord.Interaction, member: discord.Member, Reason):``` what do i put in the reason
naive briar
#

Put what in what

formal basin
naive briar
#

You should already know what to put there if you know what you're doing

#

It's like the easiest thing imaginable

formal basin
#

ok

sturdy dragon
#

Put in anything you want, you namesd the parameter reason so I’m assuming jt expects one

formal basin
#
async def kick(interaction: discord.Interaction, member: discord.Member, *, reason = "no reason provided"):``` I thought this would work
twilit grotto
formal basin
# twilit grotto that makes it so that if the reason is not passed, the default reason is 'no rea...

Yeah but i cant run my bot Traceback (most recent call last): File "main.py", line 60, in <module> async def kick(interaction: discord.Interaction, member: discord.Member, *, reason= "no reason provided"): File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 887, in decorator command = Command( File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 665, in __init__ self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 370, in _extract_parameters_from_callback raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}') TypeError: parameter 'reason' is missing a type annotation in callback 'kick' 

twilit grotto
#

try defining reason as a string and then setting default value like:
reason: str = "no reason provided"

formal basin
#

ok

twilit grotto
formal basin
formal basin
#
@client.event
async def on_app_command_error(interaction: discord.Interaction, error):
  if isinstance(error, app_commands.ValueError):
     command = interaction.app_command
     channel2 = client.get_channel(1112053260879147130)
     await interaction.response.send_message("error: number1 needs to be bigger than number2")
     await channel2.send(f"{command} command used by {interaction.user} but an error occured")
```how can i get this error handling to work
formal basin
#

how can i do button error handling

idle lantern
#

i just updates my discord py module and my bot isnt working anymore

#

turns out i have been working on 1.7 version all this time and the latest version is 2.2

#

it was a bad choice to learn from open ai

twilit grotto
formal basin
#

how can i do button error handling?

idle lantern
#

good bye

#

btw

#
# before
bot.load_extension('my_extension')

# after using setup_hook
class MyBot(commands.Bot):
    async def setup_hook(self):
        await self.load_extension('my_extension')

# after using async_with
async def main():
    async with bot:
        await bot.load_extension('my_extension')
        await bot.start(TOKEN)

asyncio.run(main())
``` which one is better to use? and how
twilit grotto
#

i believe setup_hook is better

idle lantern
#

can you explain how it works?

#

i mean

#

do i run the bot normally as bot.run(token) like before if i use setup_hook?

#

or it needs to be awaited or something?

#

and is that class auto assigned to the bot or there is a way?

#

if im saying anything stupid pls dont kill me

upbeat gust
upbeat gust
glad cradle
turbid condor
#

guys how can i make it that my bot checks if there is a user mentioned in a message like in a command for example

@bot.command()
async def send(ctx,*,message):

like in this case i want it to check if there is a mention in the message and reply with yes or no

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
#

This might be what you're after

turbid condor
#

hmm let me see

buoyant quail
#

Hi, what's the way to get the default converter for type?
I want to make my custom converter, that first tries to convert the value with it's converter and then can do something else with them.

  • how should i call that converter so it would work absolutely the same as if just typehinted the function as arg: int for example?
    will just argument = await converter.convert(ctx, argument) work?
HERE_IS_MY_COOL_TOKEN = "..."

import discord
from discord.ext import commands

client = commands.Bot(command_prefix=".", intents=discord.Intents.all(), test_guilds=[703325198086307860])

class TestArgConverter(commands.Converter):
    def __init__(self, type_):
        self.type_ = type_

    async def convert(self, ctx, argument):
        converter = ???  # get default converter for self._type 
        argument = await converter.convert(ctx, argument)
        # Some extra stuff
        return argument


@client.command()
async def test(ctx, arg: TestArgConverter(int)):
    ...


client.run(HERE_IS_MY_COOL_TOKEN)
golden portal
unkempt canyonBOT
#

await discord.ext.commands.run_converters(ctx, converter, argument, param)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Runs converters for a given converter, argument, and parameter.

This function does the same work that the library does under the hood.

New in version 2.0.
golden portal
#

this one is the public function you should use instead of a private one

buoyant quail
lean harbor
#

whats some good moderation command i could code in my bot?

slate swan
#

you can do much with it
when you have basic logic you can extend it to be able to mute everyone in a role for example

naive briar
#

Timeout 🥱

slate swan
#

okay i don't know if i'm doing this right, but seems to work:

#

maybe changing connect to connection

lean harbor
#

`thx

odd jasper
#

How can i create a embed message like this with automatic Role from the bot?

#

?

shrewd apex
odd jasper
#

Thats my code now

glad cradle
#

sigh replit

fading linden
knotty mountain
rugged shadow
#

it's been recontinued quite a while back

snow coral
#

it repeats itself

blissful badge
#

Hi! Having some trouble getting this command (entire extension actually) to work. I am adding a basic functionality to my bot so that I can do a command with a message ID and it will give me a list of everyone who reacted on it.

This is my extension currently

import discord
from discord.ext import commands

class GiveawayCog(commands.Cog, name="Giveaway"):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.command(description="Get list of users who reacted to a specific message.")
    async def reactlist(self, ctx, message: discord.Message) -> None:
        message_id = message
        channel = message.channel
        found_message = await channel.fetch_message(message_id)
        reaction_users = []
        for reaction in found_message.reactions:
            async for user in reaction.users():
                reaction_users.append(user.name)
        await message.channel.send(reaction_users)
        print ("test")

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(GiveawayCog(bot))

Its not giving an error or anything and seems to be loading it fine, but it just simply does nothing when this command is called.

#

Any ideas?

slate swan
#

Can anyone see my help post

smoky sinew
#

also there is no need to fetch messages like that, discord.Message fetches for you

#

but i don't know why your bot wouldn't be responding

blissful badge
blissful badge
snow coral
#

it repeats itself idk why

smoky sinew
snow coral
#

k

blissful badge
#

found_message = await channel.fetch_message(message_id) so I could get rid of this? @smoky sinew per what you said about discord.messages fetching it?

slate swan
#

@smoky sinew bro

hoary token
# odd jasper Thats my code now

if you use replit i'd atleast recommend using secrets to hide your token because theres a lot of people lurking on replit waiting for bot tokens that arent hidden using secrets

#

using replit in general isnt a good idea

#

unless you have a membership because in that case its somewhat decent

snow coral
slate swan
smoky sinew
slate swan
#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
blissful badge
# smoky sinew yes start with the code i sent
    @commands.command(description="Get list of users who reacted to a specific message.")
    async def reactlist(self, ctx, message: discord.Message) -> None:
        reaction_users = [user async for user in message.reactions.users]
        users = [
        user for user in reaction_users
        if user != self.bot.user
]
        await message.channel.send(reaction_users)

Better?

slate swan
#

@smoky sinew hey in this code else statement is wrong can you see why?

@commands.bot_has_permission(timeout_member=True)
  async def mute(self, ctx, member: discord.Member, duration: str = "10m", *, reason: str = "No reason"):
      if (
    ctx.author.top_role > 
    member.top_role
    and self.bot.top_role > member.top_role
    and member != ctx.author
    and member != self.bot
):
        await ctx.send("You cannot ban this user.")
      return 
      else:
        try:
            td = self._convert_to_timedelta(duration)
dry kelp
smoky sinew
smoky sinew
slate swan
smoky sinew
#

no

blissful badge
slate swan
smoky sinew
#

look at how it looks on discord

blissful badge
#

Oh, I thought how it is was correct.

#

Can adjust it

smoky sinew
#
for reaction in message.reactions:
    if reaction.emoji != "🎉":
        continue
    
    users = [
        user async for user in reaction.users()
        if user != self.bot.user
    ]

actually just use this

#

i forgot reaction was not defined

blissful badge
#

If I wanted it to be any reaction I could theoretically just remove the if reaction.emoji line right?

vale wing
dry kelp
#

perfectly fine

vale wing
#

That's single dockerfile right?

blissful badge
smoky sinew
blissful badge
smoky sinew
#

get rid of what

blissful badge
#

Oh I misunderstood what you said

#

I thought you meant it wouldnt be needed then

vale wing
#

Am I missing something

smoky sinew
#

well it will be defined but it will only get the last reaction*

vale wing
#

Is async comprehension a thing

smoky sinew
#

yes

vale wing
#

Just found it in PEP 530

smoky sinew
#

anything that implements __aiter__

blissful badge
smoky sinew
#

append each users to a users list instead of setting the users list to the list comprehension

blissful badge
#

Ok

#

Need to figure out why its not reading this Cog anyways

smoky sinew
#

did you load it

blissful badge
#

yeah through config

smoky sinew
#

what did you put

blissful badge
#

"extensions.giveaway"

smoky sinew
#

are the other extensions in the same folder and loaded correctly?

blissful badge
#

Yeah, here one sec

snow coral
#

it just repeats itself and idk how to fix it

smoky sinew
#

probably because you're running two bot instances

#

also what is the point of including the description if you're not going to use it

twilit grotto
#

you're most definitely running 2 instances of the bot

snow coral
#

the one already there didnt look good

smoky sinew
snow coral
#

idk

formal basin
#

how can i make an annotation that you need to put something in

smoky sinew
#

i know java annotation

formal basin
gilded oxide
#

does someone understand antinuke command?

#

I need help

smoky sinew
#

yes!

smoky sinew
formal basin
#

for example /kick member(you must do this) reason(you must do this)

#

how can i make the reason you must do this

slate swan
#

are you talking about slash or prefixed commands?

formal basin
smoky sinew
#

do reason: str instead of reason: str = "no reason provided"

formal basin
#

ok

gilded oxide
#
    @commands.command()
    @commands.has_permissions(guild_owner=True)
    async def antinuke(self, ctx, *, role: discord.Role, option: str=None):
        if option == "on":``` do I just add events now?
#

@smoky sinew

primal token
north kiln
#

what

smoky sinew
primal token
gilded oxide
gilded oxide
primal token
primal token
#

best of luck to you!

slate swan
#

I Have a question. How can i make it so when a user joins a vc channel it moves him in another one?

#

When he joins a specific vc*

#

Hi, can anyone help me? I'd like to make an embed verification but I can't. Here's my code:

async def verif(ctx):
    bouton_verif = Button(label="Acceder au serveur", style=discord.ButtonStyle.green, emoji=":lock:")
    view = View()
    view.add_item(bouton_verif)
    embed = discord.Embed(
        title="La verification",
        description="Veuillez cliquer sur le bouton ci-dessous pour accéder au reste du serveur. Merci !",
        colour=0x7f63d1,
    )

    embed.set_author(name="Verification")
    embed.set_image(url="attachment://verification.png")

    file = discord.File("verification.png", filename="verification.png")
    embed.set_image(url="attachment://verification.png")

    await ctx.send(file=file, embed=embed, view=view)```

basically the lembed senvois but i try to follow youtube tutorials i can't make it so that when we click on the button it adds to the person the role with this id : 1112695505856761958 can sqn help me please 
thank you in advance
#

Can you describe what are you trying to make?

#

so the command is that when I do the command +verif ( + = my prefix) it sends a embed (attachment) and I would like that when we click on the button below it adds to the person who clicked on the role with the following id: 1112695505856761958 (this is my role member) but it never works youtube tutorials so I come to ask for help here

#

Okay

#

give me a moment

slate swan
#

Where are you from?

#

France?

#
import aiofiles

@bot.command()
async def verif(ctx, role: discord.Role=None, msg: discord.Message=None, emoji=None):
    if role != None and msg != None and emoji != None:
        await msg.add_reaction(emoji)
        bot.reaction_roles.append((role.id, msg.id, str(emoji.encode("utf-8"))))
        
        async with aiofiles.open("reaction_roles.txt", mode="a") as file:
            emoji_utf = emoji.encode("utf-8")
            await file.write(f"{role.id} {msg.id} {emoji_utf}\n")

        await ctx.channel.send("Reaction has been set.")
        
    else:
        await ctx.send("Invalid arguments.")

@bot.event
async def on_raw_reaction_add(payload):
    for role_id, msg_id, emoji in bot.reaction_roles:
        if msg_id == payload.message_id and emoji == str(payload.emoji.name.encode("utf-8")):
            await payload.member.add_roles(bot.get_guild(payload.guild_id).get_role(1112695505856761958))
            return
#

Do something like that

#

guys someone can help me with my project?

slate swan
#

can we talk privatly?

#

Whats is it about

#

discord bots?

#

betting bot

#

kk

smoky sinew
# slate swan how can i make this?

detect when a person has joined a voice channel, create a new channel, and then move them to that channel, then check when everybody has left the new channel and delete it

thin raft
gilded oxide
#

can someone send me the docs to on_role_create event

thin raft
#

search it on the search bar

thin raft
#

read the path

thin raft
#

yup

#

that's it

gilded oxide
#

now

compact vapor
#

how do I make this:
@commands.cooldown(1, per=5400,)

not apply to me or administrators?

slate swan
unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
slate swan
#

you can add a logic for you and admins here

compact vapor
#

alright man thanks :)

slate swan
knotty mountain
#

How can I make it so that a loop task executes the same time every day (e.g every day at 10 am)

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
sick birch
#

Note the time kwarg

snow coral
#

how could i make profile cards?

leaden jasper
unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

leaden jasper
snow coral
smoky sinew
#

in this case you would probably want to have the background, text, profile picture, and level bar separate

snow coral
steep slate
#

@mild dome

mild dome
#

@steep slate

steep slate
#

NO!!!! Didn’t work in the Python discord

mild dome
#

Have fun changing it ❤️

rich crypt
#

just tried creating my first bot, but this discord module attribute error isn't going away, any help please?

smoky sinew
#

also that tutorial is outdated and will not work

rich crypt
#

oh really

smoky sinew
#
from dotenv import load_dotenv
from discord.ext import commands
import discord
import os

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

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot}.")

if __name__ == "__main__":
    load_dotenv()
    bot.run(os.getenv("TOKEN"))
#

just use something like this, you can keep the event

rich crypt
#

right

smoky sinew
#

the difference is the intents

#

which determines what data the discord api will send to your bot

merry cliff
#

lol

#

i thought i was being bad

#

nvm then

west comet
#

How to create a channel

#

With perms

vale wing
vale wing
unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
vale wing
#

Perms can be specified in overwrites kwarg, check docs

naive briar
#

Why not

vale wing
unkempt canyonBOT
#

__import__(name, globals=None, locals=None, fromlist=(), level=0)```
 Note

This is an advanced function that is not needed in everyday Python programming, unlike [`importlib.import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module").

This function is invoked by the [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement. It can be replaced (by importing the [`builtins`](https://docs.python.org/3/library/builtins.html#module-builtins "builtins: The module that provides the built-in namespace.") module and assigning to `builtins.__import__`) in order to change semantics of the `import` statement, but doing so is **strongly** discouraged as it is usually simpler to use import hooks (see [**PEP 302**](https://peps.python.org/pep-0302/)) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of [`__import__()`](https://docs.python.org/3/library/functions.html#import__ "__import__") is also discouraged in favor of [`importlib.import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module").
naive briar
drifting arrow
#

Anybody able to help me with something?

#

Who am I kidding? ofc ya'll can.

#

ya'll smart cookies.

#

Anyway I am storing this symbol () in a json file, but when I call it to discord it changes to • anybody know why?

knotty mountain
#

How do I catch a Missing permissions exception? I tried commands.MissingPermissions but that doesn't seem to work

drifting arrow
#

is it a slash command?

knotty mountain
#

No, its a normal command

drifting arrow
#

oh damn

#

i havent used normal commands in a while

#

that side of discordpy has been pushed out of my brain

knotty mountain
twilit grotto
slate swan
thin raft
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

thin raft
#

!d PIL

unkempt canyonBOT
#
PIL
slate swan
#
owner_roles = [1105755873625768017]
moderator_roles = [1105755873625768017, 1108524473788936253]
support_roles = [1105755873625768017, 1108524473788936253, 1108524166656819220]
locked_channels = [1109796765311442967, 1109796850397098065, 1109796957704163338]
blacklisted_words = ["123"]

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle)
    print("\x1b[38;5;41m[Success] Bot Online")

@client.event
async def on_message(message):
    if message.author.bot:
        return

    if not message.content.startswith(client.command_prefix):
        if any(role.id in owner_roles for role in message.author.roles):
            return

        content = message.content.lower()
        for word in blacklisted_words:
            if word in content:
                await message.delete()
                await message.channel.send(f"{message.author.mention} Your message contains a blacklisted word and has been removed!")
                return

    await client.process_commands(message)

basically the code is meant to delete the blacklisted message but it doesnt, any clue why

#

(thats obviously not all my code)

#

nvm i fixed it a different part of the code was interfering with it

upbeat gust
slate swan
#

its easily bypassable

upbeat gust
slate swan
#

i already said it isnt my full code + i obviously removed blacklisted_words so i dont have a bunch of slurs in chat

upbeat gust
slate swan
upbeat gust
#

alr

slate swan
#

plus this isnt gonna be a public discord bot im just making it cause yea

stark nexus
#

Hello!
I'm a beginner of coding bot
I hope i can find someone can help me create a discord bot together ^^

The bot i want make a about a game call "Splatoon" from Nintendo switch(just hope but not really needed)

vocal snow
slate swan
#

thats why you dont rely on bots

upbeat gust
#

you just said automod sucks 💀

slate swan
#

it does

vocal snow
#

exactly, manual moderation is quite essential for this, your system is just as foolproof as discord's builtin regex automod (except that one will actually prevent the message from being sent in the first place)

slate swan
#

doesnt discord automod have limits though?

upbeat gust
#

wdym limits

slate swan
#

im pretty sure the automod has limits to what you can add to it

#

python sure doesnt

vale wing
formal basin
#

how can i get the owners name on_guild_join

slate swan
#

Is it possible to use custom_id and url in buttons with discord.py v2?

stray path
#

Can anyone help me, I have 2 issues. 1: Is it possible to remove the bot from "replying" to a slash command so that it just sends a message after I use and command. And 2: How do I correctly mention everyone, I have tried to just @ everyone but it doesn't actually ping.

formal basin
stray path
formal basin
formal basin
#

idk if that would work

#

but try

stray path
formal basin
#

so you cant at everyone on your bot

stray path
formal basin
stray path
#

I do have the permission for the bot to at everyone

formal basin
#

ok 1 sec

stray path
#

I found this

north kiln
#

Why do you need your bot to mention everyone...

stray path
formal basin
stray path
#

But did it ping you?

formal basin
stray path
#

Anyway I fixed it thank you guys

formal basin
stray path
#

This is what I had it didn't have the ping

#

but whatever issue is fixed now.

slate swan
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/home/discord-bot/events/la_lfg.py", line 135, in callback
    group_chat_button = GroupChatButton(thread)
  File "/home/discord-bot/events/la_lfg.py", line 70, in __init__
    super().__init__(style=discord.ButtonStyle.green, label="Group Chat", custom_id="group_chat", url = thread.jump_url)
  File "/usr/local/lib/python3.10/dist-packages/discord/ui/button.py", line 102, in __init__
    raise TypeError('cannot mix both url and custom_id with Button')
TypeError: cannot mix both url and custom_id with Button

Is there a way to get the button to work with a custom id and url? I can work around it if not, but it would be nice to know from someone more experience here as google isn't doing me any favours. And don't really want to ruin my code with crap from google.

upbeat gust
#

custom_id is only really necessary for making components persistent

#

url buttons don't have any functionality in that sense so they don't need a custom_id

slate swan
#

Because im replacing an a LFG bot so copying some of its functionality as well as improving on it, as you can see the 1st message is a hidden only to user which is where you doing all the selections for the raid, and can then create the raid, from here its posts a public embedded thread, but the hidden messages updates with a messgae saying this raid group has been created etc with a button that links directly to the newly created thread, as this is going to be for multiple different groups, I assumed it would need to be persistent

#

The screenshot isn't my bot, this is the bot I'm going to replace with my own bot eventually.

upbeat gust
#

Ah yeah url buttons don't need to be persistent since they don't do anything on the bots side, it's all client side

#

normal buttons need to be persistent so the bot can handle it or whatever but url buttons don't

formal basin
#
@client.tree.command(name="google", description="go to google")
async def google(interaction: discord.Interaction):
  button = Button(label="google", url="https//:google.com")
  view = View()
  view.add_item(button)
  await interaction.response.send_message(view=view)```
slate swan
upbeat gust
#

Great, np

slate swan
#

I started using cogs and my bot does run and the command works but it gives an error that the command doesn't exist. Does anyone know how to fix this?

alpine cove
#

and prob also the part that loads the cogs

vale wing
#

!d discord.TextChannel.slowmode_delay

unkempt canyonBOT
desert kiln
#

Hey guys is there any way to have a bot up 24/7 for free? Without having to have my computer on the whole time

#

Please tag me when replying

alpine cove
slate swan
alpine cove
# desert kiln Hey guys is there any way to have a bot up 24/7 for free? Without having to have...

Affordable hosting providers:
• OVH Starting at $3.35/mo for 1 core, 2GB RAM, 20GB SSD
• DigitalOcean Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Linode Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Vultr Starting at $2.50/mo for 1 core, 512MB RAM, 10GB SSD
• AWS Lightsail Starting at $3.50/mo (first month free) for 1 core, 512MB RAM, 20GB SSD
• Time4VPS Starting at €3.99/month for 1 core, 2GB RAM, 20GB SSD
• VIRMACH Full Windows and Linux Desktop VPS starting at $7/mo and $1/mo respectively
• Netcup Starting at €2.62/mo for 1 core, 2GB RAM, 20GB SSD
• GitHub education Free credit and other offers for students
• Microsoft students Free credit for students
• Google Cloud free tier
• Pebblehost Starting at $3.00 1024MB DDR4 ECC, Intel Xeon E5-1630v3 / Intel i7-7700k

upbeat otter
#

or app_commands

slate swan
#

in the cog file im using app_commands

upbeat otter
#

the part where you load the cog

#

show that.

#

oh i see now

#

the reason your command doesn;t work is because

#

you don't have a self argument in the methods since it is inside a class

#

so it should be

async def command(self, ctx...)
slate swan
#

oh wait yeah right thanks

upbeat otter
#

and name ctx to interaction since app commands use interactions

slate swan
#

yeah i left the whole thing in the cog file thanks

desert kiln
slate swan
slate swan
#

Google is your friend