#discord-bots

1 messages · Page 288 of 1

final iron
#

Idc, you've been doing stuff like this for the past couple days

#

You make it pretty difficult to help you

#

I'm over it atp

harsh orbit
#

@final iron
That's correct for you?

#

I removed every try and except in command

river plank
#

How do I make a command run every 24hrs and where the time persists thru resets ?

harsh orbit
#

@final iron
Thanks for not helping and waste time

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
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).
river plank
#

Oh

final iron
river plank
#

💀 sorry mate

harsh orbit
final iron
# river plank Oh

If you want it to remain persistant through resets you'll have to setup a database

river plank
#

Ohh

#

Yea I got a database setup

#

But how will the bot keep the time before it restarts

harsh orbit
#

It's cause the bot is still in the loop or you have another idea?

final iron
river plank
#

Well so far it's intentional shut downs but your right I'll just set it up when I'm done working on my bot 💀

#

Thanks tho

final iron
#

You could use on_disconnect, but that'll happen occasionally even while the bot is running

river plank
#

Darn

final iron
#

There might be a more elegant way to do it, give me a second

river plank
#

Whats the reconnect argument in tasks ?

river plank
harsh orbit
#

Nice ingro

river plank
#

Im guessing that's not gonna make it persist ?

#

Or is it? I'm just dumb

final iron
#

I have no clue

#

You'll have to ask somebody smarter than me

#

There might be something like on_websocket_disconnect or on_heartbeat_disconnect but I can't find it right now

#

I'd ask some other people

river plank
#

Oh right but thanks a lot

#

You helped alot fr

cloud dawn
#

What are we fixing?

#

@river plank Why not just set a specific time to run it?

river plank
#

You can do that ?

cloud dawn
#

!d discord.ext.tasks.Loop.time

unkempt canyonBOT
#

property time```
Read-only list for the exact times this loop runs at. `None` if relative times were passed instead.

New in version 2.0.
cloud dawn
#

You can pass let's say 06:00 and it will run every day on 06:00 regardless of it having been shutdown.

river plank
#

I-

#

Smartass

cloud dawn
#

It takes a datetime.time object

#

!d datetime.time

unkempt canyonBOT
#

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) subclass. The remaining arguments must be integers in the following ranges...
river plank
#

So could you give me a simple example of it ?

cloud dawn
#

As a cog or just the loop function?

river plank
#

Just a loop function

cloud dawn
#

https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop.time There are already plenty of examples on the site. But specifically this will suit you the best most likely. ```py
import datetime
from discord.ext import commands, tasks

utc = datetime.timezone.utc

If no tzinfo is given then UTC is assumed.

times = [
datetime.time(hour=8, tzinfo=utc),
datetime.time(hour=12, minute=30, tzinfo=utc),
datetime.time(hour=16, minute=40, second=30, tzinfo=utc)
]

class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
self.my_task.start()

def cog_unload(self):
    self.my_task.cancel()

@tasks.loop(time=times)
async def my_task(self):
    print("My task is running!")
river plank
#

Oh damn

cloud dawn
#

For time you can also just pass a single item. Do notice that if you plan to use anything needing Discord information, guilds, members etc you would need to wait until the bot has been started.

#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook) can lead to a deadlock.
cloud dawn
#

Using this you can wait, I recommend doing that in the cog load and moving the start over there.

#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
river plank
#

Right thanks a ton panda

cloud dawn
#

Np, good luck.

vital nest
#

question how to keep the bot runing

slate swan
#

Get a VPS and run it there

vital nest
#

doyou now a free one

dusk dagger
#

Hetzner is the cheapest, however imo digital ocean is the best.

cloud dawn
#

You can also go for a containerised environment those are most of the time cheaper and run better & more reliable.

fading linden
#

is it possible to add a fast forward feature to a music bot with the FFmpegPCMAudio module?

as i understand it, i probably would need to load the entire music first in its entirety for this to work. i was looking to PyAudio for some references but I didn't find anything useful for this

#
self.vc.play(
            discord.FFmpegPCMAudio(m_music, **self.FFMPEG_OPTIONS),
            after=lambda _: self.play_next(),
        )

also one other thing,
if I were to write self.play_next() outside of the anonymous function, the bot just skips through the queue without letting any audio play. is it mandatory? I have read the docs and it said it would wait until the current stream ends but it didn't really specify how it "waits"

severe sonnet
#

okay guys, how do i send embed correctly?

#

cus i got this failure

fading linden
cloud dawn
fading linden
#

then lets speak in terms of ffmpeg and pyaudio module

cloud dawn
#

Well I can't help with this now that I know what you are doing 😅

fading linden
#

touche

fading linden
cloud dawn
#

You can always get approval from a mod then I'd be happy to help.

#

Like go forward 10 secs?

fading linden
#

yeah

#

so maybe tell me if either ffmpeg or pyaudio can do that? i just need this information i guess then I can experiment on my own, let's say to create my own audio player

cloud dawn
#

Yes you can do this.

severe sonnet
#

strange error:

  File "c:\Users\User\Documents\GitHub\RP-Utilities\cogs\CharactersCog.py", line 185, in _character_default_delete
    response = discord.on_message(ctx)
               ^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'on_message'
#

what is the correct use of on_message?

naive briar
eager mural
#

hello i have a problem with my npm better-sqlite3

naive briar
twilit grotto
#

!paste
for whoever was trying to post codeblocks

unkempt canyonBOT
#
Pasting large amounts of code

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

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

severe sonnet
#

how i should use it then, like, is there any example of using it correctly?

naive briar
#

🐈

@bot.event # (assuming that your bot's instance is named 'bot')
async def on_message(message: discord.Message):
    ... # do whatever you want with the message 
#

!d discord.Client.event

unkempt canyonBOT
#

@event```
A decorator that registers an event to listen to.

You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).

The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.

Example

```py
@client.event
async def on_ready():
    print('Ready!')
```...
naive briar
#

Oh nice, there's an example in the docs

severe sonnet
twilit grotto
#

this is the python discord 💀

eager mural
#

??

eager mural
naive briar
#

Well, this seems more like a npm thing, but judging by the errors; it looks like the program cannot find a Python executable

#

(and maybe try asking in a JavaScript server or something, this is a Python server so people here might not be able to help much)

eager mural
#

can you give me the javascript server?

#

@naive briar

naive briar
golden portal
golden portal
#

yea, since after takes a callback

fading linden
#

from the docs

The finalizer, after is called after the source has been exhausted or an error occurred.

golden portal
#

yea, but you're calling it, you didnt give it a callback

#

tbh, that lambda function is fine, because after takes a callback that will gives you 1 argument, and your play_next doesn't seems to have it

fading linden
#

that then plays it

golden portal
#

sure, or after=self.play_next, but you need to set play_next to have 1 argument

fading linden
fading linden
golden portal
#

yes

fading linden
golden portal
#

no, thats up to you if you wanna read what error was raised during the play

#

it's None when there is no error when the audio finished

fading linden
#
def play_next(self, error):
  if error is None:
    # continue the stream
  else:
    # do something

i guess in the end its going to be something like this?

golden portal
#

ehh tbh i would rather log it to see what error raised and still continue the stream

#

since i wouldn't want errors to stop it

fading linden
#

duhh

#

i guess the error itself won't stop the playback by design? it just tells us something's up

golden portal
#

yeh

fading linden
#

goot it
okok back to maintaining the bot
big thanks!

golden portal
#

oke

humble lily
#

There is any way for me to fix options with a slash command?

#

Like /warn user(discord tag), type(2w, 4w OPTION), reason

humble lily
#

Yeah

humble lily
buoyant quail
#

what?

humble lily
#
async def atgard(ctx, spelare: discord.Member, åtgärd: discord.Option):
#

Like that ^^

dusk dagger
#

There’s 3 ways to do it

buoyant quail
#

wdym like that

dusk dagger
#

Pick whatever one you’d like

buoyant quail
#

discord.Option doesn't even exist

humble lily
#

What exists then?

buoyant quail
#

The Literal is what i like. Easy and short

dusk dagger
#

Using a typing.Literal is the easiest imo

humble lily
#

NameError: name 'app_commands' is not defined

buoyant quail
#

Is it a slash command?

dusk dagger
buoyant quail
#

How you did it without importing it

#

@bot.tree.command() if you use it with bot

humble lily
#
from datetime import timedelta
from dis import disco
from email import message
from tkinter import N
from typing import Union
import discord
import json
from colorama import Fore 
import os
import threading
import fade
import time
import timer
import base64
import emoji
import httpx
import ctypes 
import json as jsond
import requests
import hashlib
from uuid import uuid4
import binascii
import subprocess
import sys
import discord, colorama, sys, os, json, pystyle
from discord import app_commands
from discord.ext import commands, tasks
from discord import Option
from pystyle import Add, Center, Anime, Colors, Colorate, Write, System
buoyant quail
#

Docs are showing the example, you are not supposed just copy randomly lol

#

from discord import app_commands

#

you have that

humble lily
#

Yep

dusk dagger
#

alright should be fine now

humble lily
#
  File "C:\Users\blomo\Desktop\Unive Kriminell Bot\sourcecode.py", line 26, in <module>
    from discord import app_commands
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
    from .commands import *
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 50, in <module>
    from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\enums.py)```
buoyant quail
#

Show pip freeze output

humble lily
#

what the fudge is that laugh_cry

buoyant quail
#

Looks like old/broken with some forks library

dusk dagger
#

Does discord.Option exist?thonk

dusk dagger
dusk dagger
#

Don’t use requests, it causes blocking.

buoyant quail
dusk dagger
#

check out aiohttp

buoyant quail
humble lily
#

I am new to this

buoyant quail
#

What library do you use?

humble lily
#

As u could tell

humble lily
buoyant quail
#

For discord

humble lily
#

ugh idk

buoyant quail
#

💀

buoyant quail
humble lily
#

This?

buoyant quail
humble lily
buoyant quail
humble lily
dusk dagger
#

You seem to have one or multiple forks of discord.py installed. These forks may interfere with official discord.py code causing possible errors. You can use the following script to uninstall any possible fork you may have installed and create a fresh install of discord.py:

import os
import sys

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

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
buoyant quail
#
pip uninstall discord
pip uninstall discord-ext-slash
pip uninstall discord-py-slash-command
pip uninstall discord.py
pip uninstall pycord
pip uninstall py-cord

pip install discord.py -U
dusk dagger
humble lily
#
  File "C:\Users\blomo\Desktop\Unive Kriminell Bot\sourcecode.py", line 30, in <module>
    bot = discord.Bot(command_prefix='.')
AttributeError: module 'discord' has no attribute 'Bot```
buoyant quail
#

discord actually has no Bot attribute

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
dusk dagger
#

The error is pretty self explanatory, a bot object is from the commands extension.

buoyant quail
#

I'd believe half of them are imported just for fun

final iron
#

regex is complicated asf but its a lifesaver

meager rock
#

more like autoimports by IDE since variables weren't defined locally

timid spade
#

till now i was storing my bots servers data like this, now when i think about it, its very dumb. like if you have something for only one guild, youre not gonna make a whole column for it
soo any suggestions how else can i save data?

#

i was thinking, maybe a table for each guild? will it work?

#

asking here because i wanna do the final this time, its not gonna be fun chaning again anf again

hushed galleon
#

columns are usually a good idea for server settings because all guilds can take advantage of it, but if you're really sure you'll never use it in other guilds, i guess putting that setting in a new table with one row is fine (i would still structure it so it could scale to other guilds, for example a dedicated guild_welcome_message table with guild ID as primary+foreign key)

timid spade
#

ah, i see, i need lil bit of thinking on it before i say anything
but yeah if youre saying this method is correct, okay i will find a way with this one

#

in short i was trying for a command which with its work can allow user to create a new colums, commands direct purpose wont be to create a column but yeah what ever it does it will require a column different in each server. but while typing it here i realised maybe that command is just useless

#

lmao

#

yeah okay, thanks man @hushed galleon

cloud dawn
maiden fable
#

The moment py-cord made that change is when I knew it's gonna suck lol

harsh orbit
#

How to disable help command?

slate swan
#

can someone help me?

#

my vc setup cmd wont work and its showing no errors

harsh orbit
#

And how to disable timeout in wait_for

golden portal
harsh orbit
#

So how to make like if the command used 2 times the first wait break

golden portal
#

what is this even for

harsh orbit
#

For example:
The command !hi make the bot waiting from you to send hello but I used the command another time so now if you send hello the bot will make the action 2 times

#

Or this disabled by default?

golden portal
#

just limit the command to be used only once concurrently for each person?

#

dont allow the command to be invoke if its not done yet

harsh orbit
#

I don't want that

golden portal
#

well, you can't achieve this with a wait_for, and its unnecessarily complicated if you want to implement that

harsh orbit
#

I want if the command used another time so the first wait breake and another one starts

harsh orbit
golden portal
#

!d discord.ext.commands.max_concurrency

unkempt canyonBOT
#

@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.
golden portal
#

just use that

harsh orbit
#

Ok I'll

#

Thx for help

harsh orbit
golden portal
#

instead of disabling it, i would assume you just wanna customize it

harsh orbit
#

I know

#

It's just temporary

golden portal
#

see the bot.help_command=... part, that's the part for help command implementation, you can remove it by setting it to None or make your own with subclassing

harsh orbit
#

Ok Thx a ton

slate swan
#

Or if you just want to disable it set help_command to None when creating bot instance

weak ingot
#

is there a way to add a sub command here
(like role add <user> <role>, role remove <user> <role>, role temp <user> <role>)

#
@bot.tree.command(name = 'addrole', description = 'Adds a specific role to a specific user.')
@app_commands.checks.has_permissions(administrator=True) 
@app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
async def addrole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
    await user.add_roles(discord.Object(id=role.id))
    await interaction.response.send_message(f'Added {role} to {user.mention}.', ephemeral = True)

@addrole.error
async def on_addrole_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)```
naive briar
#

No, you need an app commands group to do something like that

#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
weak ingot
#

thx

weak ingot
#

AttributeError: module 'discord.app_commands.tree' has no attribute 'command'. Did you mean: 'Command'?

class Roles(app_commands.Group):
    @app_commands.tree.command(name = 'add', description = 'Adds a specific role to a specific user.')
    @app_commands.checks.has_permissions(administrator=True) 
    @app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
    async def addrole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
        await user.add_roles(discord.Object(id=role.id))
        await interaction.response.send_message(f'Added {role} to {user.mention}.', ephemeral = True)

    @app_commands.tree.command(name = 'removerole', description = 'Removes a specific role to a specific user.')
    @app_commands.checks.has_permissions(administrator=True) 
    @app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
    async def removerole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
        await user.remove_roles(discord.Object(id=role.id))
        await interaction.response.send_message(f'Removed {role} to {user.mention}.', ephemeral = True)
#

i can try

slate swan
unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
slate swan
#

You are missing ()

#

In function definition

#

should be py async def on_ready(): ...

#

Its discord.ext

#

You never imported Intents?

#

!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
#

No you read the embed i sent

#

And look at the example

#

Look at the imports..

#

no? it comes with discord

slate swan
#

what package are you using?

naive briar
#

Python is case-sensitive

slate swan
#

o yeah

naive briar
#

discord.intents is not the same as discord.Intents

ember mango
#

refresh

naive briar
#

from discord import intents -> from discord import Intents 🤷

glad cradle
#

from discord.intents import Intents lmao

glad cradle
slate swan
#

to import intents but yeah

ember mango
glad cradle
#

juat?

ember mango
#

just\

slate swan
#

use has_role check

ember mango
naive briar
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
ember mango
#

item role id?

slate swan
#
@command()
@has_role(my_role_id)
async def command(...):
    ...
#

example l:

ember mango
#

good example

slate swan
#

what to expext more

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

slate swan
#

this?

buoyant quail
#

Also you could just click Copy Text button and see

buoyant quail
slate swan
#

way better

ember mango
#

How can I get someone to tell me something when I don't have the role?

slate swan
#

implicit imports

ember mango
buoyant quail
ember mango
slate swan
#

NoPrivateMessage is obviously when the command is ran in dms since there are no roles in dms

#

so the error that is being raised is MissingRole

#

add that to your error handler

#

and handle it way you want

ember mango
#

but error how to add?

ember mango
#

...

slate swan
#

yea ..

ember mango
buoyant quail
#

: )

ember mango
#

You? wow

slate swan
#

(no way)

buoyant quail
#

He is fake ducky_vader

ember mango
#

🗿

#

me me me

tepid dagger
#

code:

await interaction.message.delete(delay=5)```

error:
 File "main.py", line 51, in dont_use_this
    await interaction.message.delete(delay=5)
AttributeError: 'NoneType' object has no attribute 'delete'

why doesn't this code work
ember mango
tepid dagger
#

wdym

turbid condor
buoyant quail
#

interaction.message is None

I guess that attribute is not updated.

do

message = await send(...)
await message.delete()

Also there is delete_after attribute

tepid dagger
#

ok

ember mango
tepid dagger
#

ok

ember mango
#

this is easy

buoyant quail
#

!d discord.abc.Messageable.send

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

delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.

tepid dagger
#

k it works

turbid condor
buoyant quail
# ember mango wich one good?

I am just sending both options. Deleting the message is not what you always want. With such method you can't for example add reactions to message. But here it is good, yes.

ember mango
#

👍
\

harsh orbit
#

How I can use max_concurrency in my command

buoyant quail
#

Same as other checks :p

harsh orbit
#

I was asking because it's turned error when I did this but it was because I didn't put a number

#

Anyway

#

Thx you

harsh orbit
buoyant quail
#

?

#

Name of the error?

harsh orbit
#

Error

harsh orbit
buoyant quail
#

It's in the docs pixels_snek_2

harsh orbit
buoyant quail
#

MaxConcurrencyReached

harsh orbit
#

Ok

#

My command have wait_for and when someone use it tow times and send the same message the bot do the action 2 times so should I use before_invoke or what?

#

If you didn't understand my question please just tell me to explain and don't ingro me

buoyant quail
#

Why want you separate it? It's logically to make 2 actions if you did call the command 2 times

harsh orbit
#

For example:
When I type the command !hi now you should reply with hello to make the bot make an action but I used the command 2 times and you send hello only one time but the bot make the action 2 times

buoyant quail
#

Looks absolutely correct to me

#

You called the command two times, made needed action, got two results. One from each command

harsh orbit
#

I want make that you can't use the command another time before the first time was finshed

harsh orbit
buoyant quail
#

You'd add current command calls counter. And do like

if count == 1:
    do_action
else:
    count -= 1
harsh orbit
buoyant quail
#
if count == 1:
    do_action
count -= 1
buoyant quail
slow escarp
#

can someone tell me how to make my bot asign roles to a member with a command

#

ded chat

#

py import module from module import *

#

what does * mean

naive briar
#

Import all names from the module

slow escarp
#

can u tell me how to make my bot asign roles to a member with a command

buoyant quail
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
slow escarp
#

what does atomic mean?

buoyant quail
#

Open the link

#

atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

#

Still not very clear tho

#

I guess it means that sometimes cache can break something but with this setting it won't

slow escarp
#

so

#

await add_roles(roleid,reason=None,atomic=True

pallid meadow
#

no

slow escarp
#

?

pallid meadow
#

you only need to supply the role ids

#

the rest of the args you can leave alone because they are defaults

#

that what the = denotes in the docs

slow escarp
#

await add_roles(roleid)

pallid meadow
#

perfect

slow escarp
#

TY

naive briar
#

They probably need to be snowflakes though, not just bare integers

pallid meadow
#

na bare ints work

#

iirc

slow escarp
#

snowflakes?

pallid meadow
#

tldr everytime you create a user or a message

#

an id gets generated with that

#

and it's called a snowflake

#

so see this is my user id 670802831678373908

#

this is an example of a snowflake id

slow escarp
#

@client.command()
async def verylongcommandthatwillgiveyouaadminroleig(ctx):
await add_roles(1142768251751903312)
doesnt do

#

or i need to remove the (ctx)

pallid meadow
#

does you bot have the mannage_roles flag

slow escarp
#

it has admin

pallid meadow
#

might have to be a snowflake then

golden portal
#

no, bare int doesnt work, you would need to use discord.Object

pallid meadow
#

lemme see if I can find an example unless you had one @naive briar

unkempt canyonBOT
#

discord/member.py lines 1043 to 1051

if not atomic:
    new_roles = utils._unique(Object(id=r.id) for s in (self.roles[1:], roles) for r in s)
    await self.edit(roles=new_roles, reason=reason)
else:
    req = self._state.http.add_role
    guild_id = self.guild.id
    user_id = self.id
    for role in roles:
        await req(guild_id, user_id, role.id, reason=reason)```
pallid meadow
#

yeah i forgot about discord object

#

piece of shit class

pallid meadow
naive briar
pallid meadow
#

then instatiate it like this discord.Object(role_id)

golden portal
naive briar
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id, *, type=...)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
slow escarp
pallid meadow
#

yes

#

snowflake ids are for everything on discord though

#

users, channels, messages

slow escarp
#

class discord.Object(roleid, *, type=)

#

what to say on type?

pallid meadow
#

no

#

discord.Object(your_role_id)

#

but you would pass that as the role in the add_roles function

slow escarp
#

@client.command()
async def getadmin(ctx):
discord.Object(1142768251751903312)

#

idk

slow escarp
#

the chat dies for no reason

buoyant quail
#

Object is what you need to pass to add_roles

slow escarp
#

what does that mean cuhhhh

buoyant quail
#
await ?.add_roles(discord.Object(1142768251751903312))

? = your user idk what it is

slate swan
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id, *, type=...)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

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

hash(x) Returns the object’s hash.
slate swan
#

Thought id is keyword 🗿

slow escarp
#

BRO

#

!client.change.pressence

#

@slate swan help

buoyant quail
#

It takes only full path

#

But you can just open it in the docs /

slow escarp
#

i want to change the status of the bot

#

await client.change_pressence(status.....)

#

i know only that

#

i forgot it

buoyant quail
#

There is only one s

slow escarp
#

what

buoyant quail
#

change_presence

slow escarp
#

await client.change_pressence(status

#

what to type

buoyant quail
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slow escarp
#

status is "online, idle, do not desturb and offline" right?

ember mango
#
    info = s.get('https://api.bloxflip.com/games/crash').json()['history'][num]['crashPoint']
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/requests/models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1378, in process_application_commands
    await app_command.invoke(interaction)
  File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/slash_core.py", line 737, in invoke
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
#

What why?

#

Evry correct

buoyant quail
ember mango
slow escarp
slate swan
unkempt canyonBOT
#

class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) ‘s status.
slow escarp
#

gives syntax error

buoyant quail
slate swan
#

Need to import the Status enum

slate swan
slow escarp
#

enum?

slate swan
#

yes enum

#

Enumerable

#

!d enum.Enum

unkempt canyonBOT
#

class enum.Enum```
*Enum* is the base class for all *enum* enumerations.
slate swan
#

Doesnt really matter what it is

#

You need to import it

slow escarp
#

BRO ITS TOO HARD TO UNDERSTARD

#

from discord import status?

slate swan
#

Should have known already when making discord bot

slow escarp
#

from discord import status?
from discord import status?
from discord import status?

#

ITS NOT OMG

slate swan
slow escarp
#

i typed it

slate swan
#

thought you already know python is case sensitive

slow escarp
#

is it "from discord import status"?

buoyant quail
#

lmao

slow escarp
golden portal
#

from discord import Status it is indeed case sensitive

#

i think its best that you should start with more basic projects first before discord.py since its pretty difficult to teach you from ground zero

slow escarp
#

i know like the basic basics

golden portal
#

well, the library uses several advance concepts like OOP, concurrency

buoyant quail
#

you need more advanced basics pixels_snek_2

slow escarp
#

thats chinese for me

slate swan
#

you need to know topics like OOP, async await syntax, decorators and more

#

so if you have no idea what im talking about its prolly not time to start discord bot project

slow escarp
#

wtf is OOP

slate swan
#

object oriented programming

#

classes instances inheritance and more :D

slow escarp
#

i know "if, lists, strings, some pygame, veriables, print, else"

#

and other useless things

slate swan
#

so you got bare basics

#

now time to expand

slow escarp
#

where

#

THERE ISNT TUTORIALS

golden portal
slate swan
#

!res you can find resources here

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slow escarp
#

THERE IS BEGINNER AND HACKER NOTHING IN BEETWEN

buoyant quail
#

xdd

golden portal
#

nah, OOP is like, intermediate for python

slow escarp
#

strings and crypto finding keys and blocking a army of hackers

golden portal
#

concurrency is advance

vale wing
slow escarp
#

wrong reply

slow escarp
slate swan
#

blud talking bout the !blocking command (dont send long ass embed response)

vale wing
#

I once "hacked" my educational service and could see every student's mark for every work

#

That's funny

slow escarp
#

bro can steal my house 🙂

glad cradle
#

bro stole my house, pls help me

buoyant quail
#

we can't
we don't know "blocking a army of hackers" yet

normal lava
#

I am making a discord bot which is like Instagram

#

Will it succeed

golden portal
#

depends on you tbh

slow escarp
#

Im making something will it turn out good?
CUH HOW DO I KNOW xd

slow escarp
#

How to type it

humble lily
#

What are u stuck on?

slow escarp
#

with the !d command

#

i dont know how to use it

#

how to link my python with vsc

slow escarp
humble lily
slow escarp
#

!discord discord.intents

unkempt canyonBOT
#
Discord Bot Hosting

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

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

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

slow escarp
#

thats not what i want

humble lily
#

!d discord.Intents

#

There u have it

slow escarp
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
slow escarp
#

how to link my python with vsc

humble lily
slow escarp
#

my python ain't linked with vsc

#

and i dont have that run thing

humble lily
#

Just create a .bat

#

In ur folder

slow escarp
#

and type what?

#

im good

#

now

#

how to make my terminal more clear?

#

i dont want to see that useless stuff

mighty pilot
#

hey guys, using discord.py. i am using wait_for to get a response from the user, and im checking if that message contains a mention with if msg.mentions: but i cant seem to find a way to grab the mentioned user's ID. the msg.mention returns a list. which contains the ID. but its all one item so i cant grab just the ID

humble lily
vale wing
slow escarp
vale wing
#

Well where do you setup logging

slow escarp
#

WHAT IS LOGGING

buoyant quail
#

Windows 6 pixels_snek_2

vale wing
#

Bro has logging but doesn't know what that is

buoyant quail
slow escarp
#

how to clear that stuff in the terminal cuhhh 😭

vale wing
buoyant quail
buoyant quail
vale wing
slow escarp
#

how to delete these

naive briar
vale wing
#

It shouldn't be enabled automatically then

naive briar
#

But the bot.run automatically setup it up for you

buoyant quail
vale wing
#

@slow escarp pass log_handler=None to bot.run() it seems

mighty pilot
#

i need the mentioned member's ID

buoyant quail
vale wing
#

Cause if user mentions several just give them invalid input error or take the first

mighty pilot
buoyant quail
#

What?

mighty pilot
buoyant quail
#

It's a list of member objects

vale wing
mighty pilot
#

so why doesnt msg.mentions.id work

buoyant quail
#

Because it's a list

naive briar
#

It's a list

vale wing
#

Because list doesn't have id attribute

#

msg.mentions[0].id will if list is not empty

mighty pilot
#

oh i need to specify the position in the list. thanks

potent mulch
#

Hello, i'm still here to ask for your help.
I got this Error, don't know what i can do.

[2023-08-20 17:03:26] [ERROR   ] discord.ext.commands.bot: Ignoring exception in command test
Traceback (most recent call last):
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\simoc\OneDrive\Desktop\Comune di Roveto\DiscordBot\Comune di Roveto, Regione Toscana V2\bot.py", line 99, in test
    await channel.send(f'')
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1561, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

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

Traceback (most recent call last):
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```
#

Here's the code:

@bot.command()
async def test(ctx):
    view = Votazione()
    role = discord.utils.get(ctx.guild.roles, name="Owner")
    if role in ctx.author.roles:
        channel_id = 783597627316895744
        channel = bot.get_channel(channel_id)
        await ctx.send("What do you want to ask to the Community? _(Ricorda è una domanda Si o No)_")
        
        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel
        response = await bot.wait_for('message', check=check)

        embed = discord.Embed(
            title = f'**Votazione!**',
            description = f'``{response.content}`` \n\n *Si:* :thumbsup: - *No:* :thumbsdown:',
            color = discord.Color.green()
        )

        await channel.send(f'')
        msg = await channel.send(embed=embed)
        await ctx.send(embed=embed, view=view)
#

ok so, the code work, but the part of sending the message in a specific channel, doesn't work

#
await channel.send(f'')
msg = await channel.send(embed=embed)
naive briar
#

Read the error

HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

spiral axle
potent mulch
#

it happened the same with a different code and in the string was an response.content()

buoyant quail
#

content is a property
you don't call it
response.content

molten tapir
#

Who have vps?come pv

slate swan
potent mulch
#

Done, it works, thank you. (i'll probably come back later lol)

#

last thing, you can't ping in a Embed, right?

buoyant quail
#

No
You can only just mention user
But you can send it as a message near the embed (embed will be highlighted too)
like

await ctx.send(mention, embed=discord.Embed(...))
slow escarp
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
slow escarp
#

can someone help me

#

i fixed it

#

what to type for the status of the bot to be on do not desturb?

left dew
#

how can i check if, for example, both user1 and user2 have both clicked to a button?

naive briar
unkempt canyonBOT
severe sonnet
#

okay why my command is deleting a dict from my search?

buoyant quail
left dew
buoyant quail
#

Get the user id and append
What's the problem

#
self.clicked.append(interaction.user.id)
ember mango
#

This is true and there is no chance, but why doesn't it work? I want him to be able to use those two roles
premium_role = [1113010068712063057,1113010067940327456]

#

mean two role can use one command

#

@commands.has_any_role(premium_role)

#

@buoyant quail sy

slate swan
#

I think you have to unpack the list of roles into arguments when you pass it in

#

@commands.has_any_role(*premium_role)

ember mango
slate swan
#

Yes

ember mango
#

Did not fixed

ember mango
slate swan
#

Post the rest of the code and your traceback then.

#

For all we know it could be something else causing it to "not work"

ember mango
# slate swan For all we know it could be something else causing it to "not work"
if ctx.channel_id == premium_channel:
       await ctx.send(embed=em)
       print(f"\n{ctx.author}: Used premium_mines Command")
      else:
       response = await ctx.send("You can't use this command in this channel.", delete_after=3)
  # Delete the bot's message
      



@pre_mines.error
async def pre_mines_error(ctx: commands.Context, error: commands.CommandError):
    await ctx.send("You have not purchased premium so you cannot use this command", delete_after=7)```
#

Hello anyone here????????/

#

@buoyant quail

#

🗿

buoyant quail
#

Are you sure, that you aren't getting any other errors here?

#

Remove the handler and check the actual error

ember mango
#

@pre_mines.error
async def pre_mines_error(ctx: commands.Context, error: commands.CommandError):
await ctx.send("You have not purchased premium so you cannot use this command", delete_after=7)

#
    raise MissingAnyRole(list(items))  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
disnake.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '[1113010068712063057, 1113010067940327456]'  
buoyant quail
#

Check role ids ¯_(ツ)_/¯

ember mango
buoyant quail
#

Yes. Check that you have them. Should work

ember mango
#

.............

#

correct

#

but not work

buoyant quail
#

Send
<@&1113010068712063057> <@&1113010067940327456>
in your chat and show screenshot

#

(these are pings, don't send it on public)

buoyant quail
#

and you have one of them?

ember mango
#

i fixed

buoyant quail
hollow bolt
#

how to mention user in this

buoyant quail
#

You can't

pallid meadow
#

just mention the user above the code block

#

@pallid meadow

look
at
this
hollow bolt
#

ok

#

thanks

slow escarp
buoyant quail
#

?

slow escarp
#

somehow there wasnt client.run()

slate swan
#

..

buoyant quail
slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

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

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

If you want to search something use search field on the docs page

spring summit
#
@client.command()
async def afk(ctx, *, message="AFK"):
    afk_data[ctx.author.id] = message
    await ctx.send(f"{ctx.author.mention} is now AFK: {message}")

#(theres the on message part but im not including that since theres other shit)
  
if(message.author.id not in owners):
   if message.author.id in afk_data:
    afk_message = afk_data[message.author.id]
    await message.channel.send(f"Welcome back, {message.author.mention}! Your AFK message: {afk_message}")
    del afk_data[message.author.id]

        # Check if any mentioned users are AFK
    for user in message.mentions:
     if user.id in afk_data:
      afk_message = afk_data[user.id]
      await message.channel.send(f"{user.mention} is AFK: {afk_message}")

    await client.process_commands(message) ```
#

the bot for some reason sends the message 3 times, why

#

as in, youre afk, welcome back, youre afk

#

?

slate swan
#

no idea the if(message.author.id not in owners): is on indent level 0 is it still part of the command?

buoyant quail
#

It's not in the command at all as i understood

#

It's in on_message event

#

That's what confused me too

buoyant quail
#

So it is inside the command?

spring summit
#

it is, indeed

slate swan
#

so why are you processing commands, .. , inside a command?

buoyant quail
#

Then why are you calling process_commands there?

slate swan
#

sorry he named it client

#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message) event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message) event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context) followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke).

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context) or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke) if so.

Changed in version 2.0: `message` parameter is now positional-only.
spring summit
#

oh nvm i wasnt understandin watchu were sayin

#

and no this is on_message

buoyant quail
#

Are there others process_commands in that on_message?

slate swan
#

on_message is called on each message sent

slate swan
#

print out message.content and see what messages are invoking it

#

then work out why its 3 times and not once

#

maybe you are missing some simple check

spring summit
#

maybe im an idiot hollon

buoyant quail
slate swan
#

cause i know it is

#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
spring summit
buoyant quail
#

Man edited the source code :p

slate swan
#

blud using his own fork

spring summit
# spring summit

the mssage owner part is the bots id. so it shouldnt be called no?

slate swan
#

to see which messages invoke it

buoyant quail
#

This part of the code shouldn't then.
But yeah, always easier to just debug instead of guessing. Especially when we have only part of code /

spring summit
buoyant quail
#

Actually how did even got to the command..
I just understood that commands are processed only after checking if id is inside afk_data.. And i guess it's empty in the beginning
Even more - commands sent by owners shouldn't be executed

#

!paste the code, that will be easier

unkempt canyonBOT
#
Pasting large amounts of code

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

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

spring summit
buoyant quail
#
if message.author.id not in owners:
    await client.process_commands(message)
#

If your id is inside the owners, this condition will give False
And you wan't reach the command processing part

spring summit
#

you want me to process it twice? 😭

buoyant quail
#

Of course not
I can't understand how is it even running commands by you

dusk dagger
slate swan
#

just use @bot.listen() decorator and no need to worry about processing commands

buoyant quail
#

You are doing process_commands inside bot.listen?

spring summit
dusk dagger
buoyant quail
slate swan
spring summit
#

it does the same exact thing idk why

slate swan
#

just naming issues

dusk dagger
#

I suggest you name your bot object bot instead of client because its extremely misleading

slate swan
#

client = commands.Bot(...) is the same as import numpy as pandas

buoyant quail
#

Command is executed before the on_message in the bot.listen()
So you are setting user afk, then it goes to listen and saying it's not afk more

#

But i am still wondering how are you joining if message.author.id not in owners condition

slate swan
#

how do you know what owners is

buoyant quail
#

I am hoping...

slate swan
#

name doesnt really matter as we can see already

buoyant quail
#

mhm yeah

#

okay, but why did it give the same result with different call order (command-on_message / on_message-command)

#

though we don't know what actually happens :p

#

What are the exact messages that you get after calling .afk?

spring summit
#

owners is the bot id in case you were wondering

buoyant quail
#

xd

#

okay then i remove that question

spring summit
#

...

buoyant quail
#

why bot id is named owners

slate swan
#

told ya

spring summit
buoyant quail
spring summit
#

you typed "lmao" 3 times while saying bs

spring summit
slate swan
spring summit
slate swan
#

no idea im not really listening for long 5 mins

buoyant quail
#

@spring summit Specially for you I copied and runned your code. I don't see "sends the message 3 times" with the parts of code you decided to give us

About bot.listen() - that will give 2 messages here - "...is now AFK", "Welcome back ...". But also not 3.

slate swan
#

Not documentation

buoyant quail
#

Yes

slow escarp
#

uhmm

mossy jacinth
#

Is it possible to view a members server list and compare it to a list in json? And if it matches the server id kick or ban him? I've seen some bots that do that but i dont know how...

upbeat falcon
#

Anyone help me fix these errors

#

Its from this

mossy jacinth
# upbeat falcon

try moving from discord.ext import commands below import discord

cold sonnet
#

blud don't know what he talking about

mossy jacinth
#

fr

upbeat falcon
#

I have a moderation bot template

#

And I just wanna use it

#

Sorry if I am dumb

cold sonnet
#

check your python interpreter

upbeat falcon
#

whats that

cold sonnet
#

your python version should be at bottom right of vsc

#

or bottom left

upbeat falcon
cold sonnet
#

idk I haven't done this in a while

#

yeah you have to install discord for the right python version

upbeat falcon
cold sonnet
#

pip install discord

upbeat falcon
cold sonnet
#

maybe pip3.10 install discord

#

I dunno your python interpreter bro

upbeat falcon
cold sonnet
#

should say it at the bottom

upbeat falcon
#

it is 3.11

cold sonnet
#

then do pip3.11 install discord

heady locust
#

i kinda have the same problem,i tried installing the discord module using pip install discord/pip install discord.py,and i stii got the error called "no module named 'discord'"

#

any suggestions?

cold sonnet
#

what python version does it say at the bottom of vsc

heady locust
#

it s 3.10

cold sonnet
#

I see

#

what about pip3.10 install discord

heady locust
cold sonnet
#

damn

heady locust
#

maybe if i will use vsc the problem will vanish?

#

cause i didn't tried

cold sonnet
#

no that's not the problem

heady locust
#

well what could it be,bcs i already tried a lot of tutorials and it still does the same thing

cold sonnet
#

someone on stackoverflow said he just updated pip

#

pip3.10 install --upgrade pip

#

then pip3.10 install discord again

heady locust
#

the error still pops up

cold sonnet
#

I dunno I think something's wrong with your python installation

heady locust
cold sonnet
#

no

#

you specified python 3.10 when you ran the command

dusk dagger
#

Did you install it in the venv of your file?

#

Did you try restarting pycharm or your pc?

vale wing
#

@heady locust what's your OS

harsh orbit
#

How I can get the id of the channel from a message id?

glad cradle
#

!d discord.Message.channel

unkempt canyonBOT
buoyant quail
#

Actually looks impossible.. Discord.py has only Messageable.fetch_message, so you should already have the channel
Except if you will iterate over channels, but it's very bad option.. + If there are not global fetch_message it looks like message id can be the same in different places

meager rock
#

Message IDs are unique but yeah you cannot get the channel ID through message ID as the only data present

harsh orbit
#

@buoyant quail Bro I did what you said but didn't work

#

About you can't use the command another time after the first time end

fair badger
#

I think

harsh orbit
fair badger
#

I know this is irrelevant but it may be of use to someone

meager rock
fair badger
#

Yeah that's why I said it was irrelevant

frosty beacon
buoyant quail
# harsh orbit Can you explain it more

like this (you can use anything you want as key, i guessed you want the user)

active = defaultdict(int)


@bot.command()
async def foo(ctx):
    active[ctx.author.id] += 1

    await bot.wait_for("message", check=lambda m: m.content == "hello")
    if active[ctx.author.id] == 1:
        await ctx.send("hi!")

    active[ctx.author.id] -= 1
buoyant quail
#

There are another examples without GroupCog

frosty beacon
buoyant quail
#

for example 8
10 too

but actually i don't like how they are made in dpy

harsh orbit
buoyant quail
#

depends on what will you use as key

frosty beacon
frosty beacon
harsh orbit
gloomy beacon
#

I have decided to make my new bot in python since npm is having a stroke and cannot download discord.js

#

small problem I have no idea of how python works so this'll be fun

#

sooo uhm, do I actually just not need semicolons?

buoyant quail
#

from collections import defaultdict
you can use a standart one, but i's one line more :p
(to .Hadi.)

gloomy beacon
#

and I don't have to specify the data type

buoyant quail
#

Yes

#

It's the same for js pixels_snek_2

gloomy beacon
#

ah right; I mostly use c# so that's that. although I am rather incompetent

#

sooo, dotenv wasn't installed correctly

fiery girder
#

@tree.command(name="Warn",description="Warn A Member")
@bot.command()
@commands.has_role(872416856940642344)
async def warn(ctx, member: discord.Member, reason= "Not Defined"):
    await member.send("You Have Been Warned! From The FedxD Server.\n"
                      f"Reason: {reason}")
    await ctx.reply(f"{member.mention} Has Been Warned")

it doesnt work because i have tree.command and bot.command both init but i have seen some bots with both can you guys tell me how to do it

buoyant quail
#

You seen them as code?

fiery girder
#

no

#

like mee6

frosty beacon
#
from discord import app_commands, Interaction
from discord.ext import commands

@app_commands.guild_only()
class Chat(app_commands.Group, name="chat"):

    @app_commands.command(name="start", description="start chat...")
    async def start(self, interaction: Interaction):
        print("Launching chat session")
        await interaction.response.send_message("start chat...", ephemeral=True)

async def setup(bot: commands.Bot):
    bot.tree.add_command(Chat())
buoyant quail
fiery girder
#

how

gloomy beacon
#

alright, I am not able to import anything

buoyant quail
#

!d discord.ext.commands.hybrid_command
and the docs ofc

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand).

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command).

The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer) with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string) type.

Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction).

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

New in version 2.0.
harsh orbit
#

Is that right?

fiery girder
#

is there any practicle example rthe docs doesnt show any practicle example on how to use it

gloomy beacon
buoyant quail
frosty beacon
#

I tried the hybrid cmd, The text based command is working but / not wokring

fiery girder
#

will the command.has_role() work with hybrid commands

buoyant quail
#

It should

fiery girder
#

ok

buoyant quail
#

The easiest way to check is to try it

harsh orbit
fiery girder
#

and is using command.guild important for hybrid cause i dont want to just allow commands on one server

#

app_command.guild**

buoyant quail
#

Shortly just calling await bot.tree.sync() is enough

harsh orbit
buoyant quail
#

I didn't understand

slow escarp
#

what is a python interpreter?

harsh orbit
#

If someone use the command he get point (active) and if he have a point the command will work so this didn't solve my problem

fiery girder
#

so many mixed things man i searched on youtube and the guy made a class for Bot and it the github its dont diffrent what should i go with

harsh orbit
#

He can use it 2 times and work so he should get point after finish the command

slow escarp
#

cuz vsc wants it and i cant run programs that way

buoyant quail
buoyant quail
turbid condor
#

Yt tutorials are old

slow escarp
#

so i need to find where my python.exe is at and link it with vsc?

buoyant quail
#

It seems so

frosty beacon
turbid condor
frosty beacon
#

worked!!!!!! thanks D:

buoyant quail
turbid condor
turbid condor
#

All you have to do is just install python extension and you are good to go

buoyant quail
fiery girder
#

do i have to write the guild

#

class Bot(commands.bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix='!', intents=intents)

    async def setup_hook(self):
        await self.tree.sync(guide = discord.Object(id=872416856940642344))
#

its some thing like this

buoyant quail
#

guide
guild
pithink

fiery girder
#

oh

harsh orbit
#

User sends the command !hello now he get a point in active var and the bot waiting from you to send hi so he used the command another time before you send hi so the command will work cause when he type it he get point and when he get point the command will work

fiery girder
#

lol

harsh orbit
#

Without the wait_for ends

fiery girder
#

what do i write in the guild

#

tell me

slow escarp
#

somethings happenng with my discord bot

#

when i type !test it should say "bot is good." once but it says it like 4-5 times

fiery girder
#

WHAT SHOULD I WRITE IN GUILD

slow escarp
#

ur server id

fiery girder
#

what if i want multiple servers

buoyant quail
#

Just don't pass guild arg then

slow escarp
#

multiple server ids

naive briar
#

Just sync globally

fiery girder
#

kok

harsh orbit
slow escarp
#

when i type !test it should say "bot is good." once but it says it like 4-5 times. how to fix it?

buoyant quail
#

So you want not just skip the actions and second command, but wait for the end of first?

slow escarp
#

who?

buoyant quail
#

.Hadi.

harsh orbit
naive briar
#

What?

buoyant quail
#

Also show that command

harsh orbit
# naive briar What?

If someone use the command twice the bot will wait for 2 messages I want make him can't use it another time before the first wait ends

buoyant quail
#

Maybe just allow calling only one command at once ?

fiery girder
#

bruh can some one like link me a project with hybrid commands in use i cant get it github one is just so confusing he didnt even have the prefix defined

harsh orbit
harsh orbit
naive briar
#

Just use queues or even lock the thread at this point

#

!d asyncio.Queue

unkempt canyonBOT
#

class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.

If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.get).

Unlike the standard library threading [`queue`](https://docs.python.org/3/library/queue.html#module-queue), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.qsize) method.

Changed in version 3.10: Removed the *loop* parameter.

This class is [not thread safe](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading).
buoyant quail
unkempt canyonBOT
#

@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.
buoyant quail
#

you can set it per-user or per something else

#

i am not sure what exactly you want

harsh orbit
harsh orbit
#

Explained in docs?

buoyant quail
#

second argument

#

per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up to number times per guild.

harsh orbit
#

I will try that

buoyant quail
fiery girder
#

well i made it work somehow

#

vs code is worse then pycharm pychamr is easier for python but i uninstalled it because visual code can run many lanugages and i am currently working on python java and cpp so i needed it i wished i didnt switch

#

i prob didnt need a externet website for the developer badge lol it was easy pretty much

slow escarp
#

how to fix it?

fiery girder
#

import discord in terminal

#

pip install discord

slow escarp
#

and restart vsc?

fiery girder
#

no

#

just type in terminal
pip install discord

#

and after like a few secounds it will be fixed

#

it wll take time to download

slow escarp
fiery girder
#

did you pip install discord in the terminal?

slow escarp
#

yes

fiery girder
#

in the correct folder??

slow escarp
#

right?

fiery girder
#

yea

#

then idk

slow escarp
#

i still have this

fiery girder
#

can you show the code

#

the first 5 lines

harsh orbit
#

How to set user?

buoyant quail
#

You missed the BucketType

slow escarp
buoyant quail
#

And why you are writing the full path

#

at least import commands

harsh orbit
#

I import them but IDK how to use this

buoyant quail
#
discord.ext.commands....
=
from discord.ext import commands
commands...
fiery girder
# slow escarp

ok result is that discord package is not instaled corectly in the folder

buoyant quail
#
commands.BucketType.user
harsh orbit
#

Ok

slow escarp
fiery girder
#

yea

slow escarp
#

where can i download the discord package?

fiery girder
#

you dont have discord downloaded on another python file?

slow escarp
#

idk

fiery girder
#

cause i dont think you can download it manually like that

slow escarp
#

i have two files for the same bot

fiery girder
#

both of them not work?

slow escarp
buoyant quail
#

but it's not the best way of installing library :p

slow escarp
#

it isnt supoosed to do that

rose frost
#

Hello, I'm OpenAI's AI. How can I assist you today?