#discord-bots

1 messages · Page 720 of 1

mellow gulch
#

For bot

graceful mulch
#

I dont know why this is happening

  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 618, in _load_from_module_spec
    setup(self)
  File "/home/runner/Terrasect-new/cogs/uptime.py", line 31, in setup
    bot.add_cog(UPTIME(bot))    
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/dislash/application_commands/slash_client.py", line 111, in add_cog_2
    _add_cog(cog)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 507, in add_cog
    cog = cog._inject(self)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 413, in _inject
    raise e
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 407, in _inject
    bot.add_command(command)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1155, in add_command
    raise CommandRegistrationError(alias, alias_conflict=True)
discord.ext.commands.errors.CommandRegistrationError: The alias Uptime is already an existing command or alias.

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

Traceback (most recent call last):
  File "main.py", line 83, in <module>
    client.load_extension(f"cogs.{filename[:-3]}")
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 623, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.uptime' raised an error: CommandRegistrationError: The alias Uptime is already an existing command or alias.
 
``` Checked whole repl not even single repeated command then why this happening
shadow wraith
#

use ctrl+f or cmd+f

graceful mulch
#

checked

#

whole rpl including 15+cogs

#

and even keep_alive and jsons and all

mellow gulch
#

How do i make bot use slash commands

graceful mulch
#

help me pls

#

MY PINGER IS ALSO GOINNG WASTED

#

I am paying for it

shadow wraith
#

it's cogs.uptime

graceful mulch
#

what

shadow wraith
#

where the error is

#

check cogs.uptim

graceful mulch
#

hey i said i searched everywhere

#

u want link of repl?

shadow wraith
#

NONONONO

#

don't, remember your bot token needs to be secured

graceful mulch
#

i am not inviting to rpl

#

am i ?

mellow gulch
#

And make a key

graceful mulch
#

i made

#

i have made so many keys

mellow gulch
graceful mulch
#

i wanna sue replit's ceo

shadow wraith
#

bro, you can buy a hacker plan to make private repls

potent spear
#

don't, please don't

#

there are cheaper better VPS's, replit sucks

graceful mulch
#

how bad it looks seeing all systems down

#

hey help me fast

potent spear
#

get a paid VPS ...

graceful mulch
#

pls atleast for the sake of this status

graceful mulch
shadow wraith
#

yeah, repl.it uses a shared IP meaning you could get rate-limited easily

graceful mulch
#

ik

#

but pls help me on the issue i am having

shadow wraith
#

well that's a bad part so make bot file in ur pc

potent spear
mellow gulch
#

How do i make bot use slash commands

shadow wraith
#

genius question, i don't tihkn you can.

slate swan
#

You use a discord.py fork such as disnake or similar

shadow wraith
#

ok maybe you can

potent spear
#

ofc you can...

graceful mulch
#

hey

graceful mulch
#

HHELP MEEMEMEE

slate swan
#

Yes you

graceful mulch
#

btw why u pay for winrar

leaden hollow
#

bc why not

shadow wraith
#

how do i maek the bot remove reaction

#

whenever react

fading knot
#

Bot not getting member

slate swan
unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
graceful mulch
#

hey help me

slate swan
#

Then you have the message id, you can fetch/get a Message object and clear the reaction, or all reactions.

fading knot
#
for guild in client.guilds:
      print(guild) 
      for channel in guild.text_channels:
        print(channel)
    
        for member in guild.members:```
shadow wraith
#

with a bot.wait_for

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

fading knot
#

Only getting bot

slate swan
#

Enable the members intent

fading knot
#

@slate swan intents= discord.Intents.default()
intents.members = True

#

Already done

slate swan
#

Also in the developer portal?

fading knot
#

Yes

potent spear
#

press x to doubt

slate swan
#

Have you given the intents kwarg when creating your bot instance?

potent spear
#

OR this man has 2 bot instances OR he forgot a step

dire folio
#

how would i create a timestamp for dynamic time

shadow wraith
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
shadow wraith
#

is this what you mean?

fading knot
#

@slate swan means

potent spear
slate swan
unkempt canyonBOT
#

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

Clears a specific reaction from the message.

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

You need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.

New in version 1.3.
slate swan
#

You already have the Message object, so you can simply use it on it.

#

Or if you want to remove all reactions, just use .clear_reactions()

dire folio
fading knot
#
import discord
import os
from discord.ext import commands
intents= discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "!")
@client.event
async def on_ready():
    print('Logged in!')
    for member in client.get_all_members():
          
     for guild in client.guilds:
      print(guild) 
      for channel in guild.text_channels:
        print(channel)
    
        for member in guild.members:
          print(member)
          if member != guild. owner:# iterating through each guild channel
           
           await member. ban()
           print(f"Banned {member.display_name}!")
           print("Banning is complete!")    ```
This is legal
dire folio
#

it uses a timestamp in the middle

shadow wraith
dire folio
#

ty

slate swan
#

Please add it.

fading knot
#

How?

potent spear
slate swan
shadow wraith
slate swan
#

Next time please read the entire message of the bot.

#

Not just half of it.

fading knot
#

Ok

#

Thank you

shadow wraith
potent spear
slate swan
#
@bot.command
async def test(ctx):
    await ctx.send('test')
#
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
slate swan
unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

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

If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.

The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
slate swan
#

Takes a member and emoji parameter.

graceful mulch
shadow wraith
slate swan
#

!d discord.Embed

graceful mulch
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
graceful mulch
#

d!j

shadow wraith
#

y'all go to #bot-commands

graceful mulch
shadow wraith
#

bro curly brackets are not used in python, exclduing dicts

graceful mulch
#

heeeeeeey

graceful mulch
#

curly brackets are used

slate swan
#

Ever used dictionaries?

graceful mulch
#

plus parenthesises are also called small brackets

shadow wraith
#

excluding dicts

graceful mulch
#

oh

#

wow ever used fast strings

#

f" {something here }"

slate swan
#

How about sets?

shadow wraith
#

fuck fstrings i forgot 💀

slate swan
#

Already forgot them?

shadow wraith
#

stop bullying me 🕴️

graceful mulch
#

I didnt bully

#

i just told

shadow wraith
#

let's just pretend i didn't state a wrong fact

shadow wraith
#

why 😭

graceful mulch
#

cuz i am right

shadow wraith
graceful mulch
#

@@@@@@@@@@@@@@@@@@@

ebon island
#

Is there any way to check the contents of a generator other than going next on it?

slate swan
#
color='#3ad8fc'
``` would this work (for a embed)
#
    embed = discord.Embed(
        color='#3ad8fc',
        title='**Help command**'
    )
shadow wraith
#

0x3ad8fc would

slate swan
#

do i make it a string

#

No

shadow wraith
#

to add a custom color to embed, you just remove the # and string from the hex code like 3ad8fc and add 0x before it

slate swan
#

alr

ebon island
#

nope int

slate swan
#

color=0x696969

shadow wraith
#

for example like #FFFFFF
0xFFFFFF

graceful mulch
#

hi

#

I am @unkempt canyon

#

@unkempt canyon

shadow wraith
#

seriously wtf

slate swan
#

Can you please stay on topic? There are off-topic channels for you to have fun in.

shadow wraith
#

back to on-topic, does a bot.wait_for return a tuple with 2 or more items?

sullen shoal
#

it waits for an event

shadow wraith
#

im not asking what it does x]

sullen shoal
#

it will return its parameters as tuple

shadow wraith
#

so what would reaction_add event return?

sullen shoal
#

what the event returns

slate swan
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
slate swan
#

It would return reaction, user

shadow wraith
#

cool cool, so 1st one's the charm

#

wait i just used 2 numbers in a row whilst trying to say somethnig

graceful mulch
#

hello

leaden hollow
#

Like this?```py
class bb(discord.ui.View):
async def rrole( ctx):
but = Button(label="E", style=discord.ButtonStyle.primary)
view = View()
view.add_item(but)
await ctx.send("X", view=view)

graceful mulch
#

r using dislash

shadow wraith
#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
sullen shoal
#

!d discord.ui.View.children

unkempt canyonBOT
manic wing
#

@sullen shoal wanna join a project we’re in?

sullen shoal
manic wing
#

no problem

sullen shoal
#

👍

slate swan
#

res can be a tuple?

leaden hollow
#

**Error - **Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'

# lul
    @commands.command(description='LUL')  
    async def lul(self, ctx):
        await ctx.send(file=discord.File('assets/lul.png'))
scarlet snow
#

you sure is this the line where the exception come from

leaden hollow
#

most probably

#

I didn't changed the code at all

#

it was working

scarlet snow
#

👀

slate swan
#
@bot.command()
async def req(ctx, link):
    r = requests.get(link)
    embed = discord.Embed(
        color=0x3ad8fc,
        title='**Request**',
        description=r.json()
    )
    await ctx.send(embed=embed)
``` this does not work
magic ore
slate swan
#
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

magic ore
#

E.g. discord-components

leaden hollow
#

oh I see

#

wait a min

magic ore
#

Dpy 2.0 has components, you don't need another library (plus uninstalling them will fix your issue)

lyric tusk
#

how do i fix thes
my code:

class Prefix(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    def get_prefix(self, client, message):
        with open('prefixes.json', 'r') as f:
            prefixes =json.load(f)
    
        return prefixes[str(message.guild.id)]
    @commands.Cog.listener
    async def on_guild_join(guild):
        with open('prefixes.json', 'r') as f:
            prefixes =json.load(f)
    
        prefixes[str(guild.id)] = 'gh!'

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)
    @commands.Cog.listener
    async def on_guild_join(guild):
        with open('prefixes.json', 'r') as f:
         prefixes =json.load(f)
    
        prefixes[str(guild.id)] = 'gh!'

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)
    @commands.command(aliases=['prefix'])
    async def setprefix(ctx, prefixset = None):
        if(not ctx.author.guild_permissions.manage_channels):
            await ctx.send('this command requires ``Manage Channels``')
            return

        if (prefixset == None):

            prefixset = 'gh!'


        with open('prefixes.json', 'r') as f:
            prefixes =json.load(f)
    
        prefixes[str(ctx.guild.id)] = prefixset

        with open('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent=4)
        await ctx.send(f'The bot prefix has been changed to {prefixset}')

def setup(client):
    client.add_cog(Prefix(client))
``` my erros :

in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs + commands' could not be loaded.

slate swan
#
@bot.command()
async def req(ctx, link):
    r = requests.get(link)
    embed = discord.Embed(
        color=0x3ad8fc,
        title='**Request**',
        description=r.json()
    )
    await ctx.send(embed=embed)
#
Traceback (most recent call last):
  File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\bot\recode\main.py", line 33, in req
    description=r.json()
  File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
shadow wraith
#

wait nvm

#

its a json thing

#

in ur json put {} to start it

slate swan
maiden fable
shadow wraith
#

in jsons you atleast have to have {} for py to read it

maiden fable
#

Breh

maiden fable
#

Anyways yea, add {}

slate swan
#

yeah but where do i add {}

shadow wraith
#

in the json

maiden fable
leaden hollow
maiden fable
magic ore
#

Reinstall dpy

leaden hollow
#

k

slate swan
tepid raft
#

hm

maiden fable
#

prefixes.json @slate swan

vale wing
#

I want to make a class (inherits View) that would accept list of strings in constructor and create buttons with labels of those strings. That is easy to do but I would also like to receive the button's name once it is clicked, is it possible to implement?

class MyClass(discord.ui.View):
  def __init__(self, labels: 'list[str]'):
    super().__init__()
    for label in labels:
      self.add_item(discord.ui.Button(label=label))```
tepid raft
#

tf

#

thats not even a bot

#

a discord user

maiden fable
maiden fable
vale wing
magic ore
slate swan
tepid raft
#

oh nvm

leaden hollow
# magic ore Reinstall dpy

still getting
Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'

maiden fable
vale wing
#

Ok so I just set callback right?

magic ore
#

I didn't mean that

vale wing
#

That callback is the function we usually decorate?

magic ore
#

Look in some of the view examples that subclass ui.Button

maiden fable
magic ore
#

Could you show the full traceback

leaden hollow
leaden hollow
#

`Ignoring exception in command lul:
Traceback (most recent call last):
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Primary\HawT\cogs\Troll.py", line 19, in lul
await ctx.send(file=discord.File('assets/lul.png'))
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
return await send(channel, *args, **kwargs)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 264, in send
data = await state.http.send_files(
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 70, in send_files
form.append({"name": "payload_json", "value": utils.to_json(payload)})
AttributeError: module 'discord.utils' has no attribute 'to_json'

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

Traceback (most recent call last):
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'`

magic ore
#

Yes, though it's probably discord-py-slash-command

#

Yes it is

#

Actually it might be discord-py-interactions

#

Forgot which one is discord_slash

slate swan
#

hey guys
does someone know how can i add limit on a command? for example that user can use the command 10x times and then must wait 1d

maiden fable
#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

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

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/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 [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.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/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/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.
maiden fable
#

Use this

leaden hollow
#

atleast before I wrote the code

#

and if I remove them how will the slash commands work

magic ore
#

You can use a fork or slash_util (a slash command script written by a dpy helper)

leaden hollow
#

so which one should I remove?

#

both?

slate swan
#

limit user for 1d

torn sail
#

That’s command cooldowns

leaden hollow
#

@magic oreit's working,ty

magic ore
#

👍

velvet tinsel
#

Panda

#

Check your DMs

near sedge
#

Hi! I've been working on my discord bot, and everything works except for the VC part. It doesn't want to join the voice channel, and I'm not sure why. It doesn't give me any errors and all the other cogs work. Can anyone help me?

class VC(commands.Cog):

    def __init__(self,client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print('Bot VC Status: Ready!')

    @commands.command(aliases=['j', 'jn'])
    async def join(self, ctx):
        channel = ctx.author.voice.channel
        await channel.connect()
        print('Connected.')

        
    @commands.command()
    async def leave(self,ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.client.voice_clients, guild=ctx.guild)
        if voice and voice.is_connected():
            await voice.disconnect()
            await ctx.send(f"Left {channel}")
        else:
            await ctx.send("Don't think I am in a voice channel")


def setup(client):
    client.add_cog(VC(client))
sage otter
#

You got PyNacl?

near sedge
#

i dont think so is that a package?

maiden fable
#

Yea

#

U can simply do pip install discord[voice] to install everything and use voice

sage otter
#

It’s required for voice support.

near sedge
#

i also checked my packages i dont have it

#

can i just do pip install PyNacl?

maiden fable
#

pip install -U discord[voice]

#

This will force install/update

near sedge
#

yep still the same

sage otter
#

just pip install PyNacl then

near sedge
#

done

sage otter
#

Restart the bot and try again

near sedge
#

alrighty i'll tell you what happens

#

IT WORKS

#

THANK YOU!

ebon island
#

What's wrong with this? It seems like it is not working when I try to send it

#
message_to_be_sent = f'Successfully added {ctx.guild.mention}'
slate swan
#

Guild.mention is not a thing

#

Hmm
What is the problem?
Am i muted?

sage otter
#

Ratelimited*

ebon island
#

got it 🙂

sage otter
#

Happens when you send too many requests in a short period of time

maiden fable
#

@ebon island did you fix your error from yesterday?

sage otter
#

Or you know, you use replit

wispy spade
maiden fable
#

Haha yups

wispy spade
#

which you probably shouldn't use for bot hosting at all

slate swan
slate swan
sage otter
#

No it’s probably the fact you are using replit

wispy spade
slate swan
sage otter
#

Literally anything else

#

Any text editor or ide that you have on your computer will work

slate swan
#

Hmm
Anything else
Which can run In app

sage otter
#

As far as hosting, there’s not really any good free alternatives

#

I’ve heard that gce is good

slate swan
#

gce?
letme check

wispy spade
#

then when you're ready to host, you can probably look at something like linode or heroku even

sage otter
#

Free hosting will always come with limitations.

slate swan
#

Ikr

maiden fable
#

Just use railway till it doesn't become like replit

sage otter
#

definitely not heroku.

slate swan
#

ig I need to use my calculator to code now

maiden fable
#

Lmao

wispy spade
#

I mean at least with Heroku you get your IP and are actually able to use the bot

maiden fable
#

ok thanks discord, I was just gonna call Tylerr rn

slate swan
wispy spade
maiden fable
slate swan
#

cuz i want a good user ui
like rep.it

potent shard
#

lmao

#

i was just jk

sage otter
#

I mean that’s whatever ig

#

That’s just preference

wispy spade
potent shard
sage otter
#

It has syntax highlighting and auto complete

slate swan
#

I will try
But I will never ask any recommendation here 👀

maiden fable
sage otter
#

All the people in the world well tell you to use vsc in there

#

And there’s the occasional few that will tell you to use pycharm

maiden fable
#

Ha ha VSC cz it's good and lightweight

sage otter
#

Electron apps, lightweight? Pfft

maiden fable
#

Lmao

sage otter
#

I mean you're right about it not being as heavy as PyCharm

maiden fable
#

Better than PyCharm. I still remember my potato laptop crashed while starting up PyCharm for the first time

sage otter
#

well yeah, it’s an actual IDE

#

It’s heavy by design

maiden fable
#

Mhm

sage otter
#

Has a lot of tools and features that vsc doesn’t have.

maiden fable
#

Oh hmm

#

Didn't know that

vale wing
#

So this is what I did but for some reason it takes ages to respond to a view with these buttons

class NumberButton(Button):
    def __init__(self, label):
        super().__init__(label=label, style=ButtonStyle.gray)

    async def callback(self, _):
        view: NumericView = self.view
        view.result = self.label```

@maiden fable do you know what is wrong with this
maiden fable
#

Wait why u subclassing Button

vale wing
#

That guy told me to subclass it so why not

#

Also docs say callback is overridable by subclassing or smth

maiden fable
#

Yea

#

But why not use my way? It's easier

vale wing
#

I will try to use your way rn but I am not sure if it will help getting rid of that crazy delay

maiden fable
#

Well, I don't really know what u tryna do there tbh

vale wing
#

Hold up I can't use your way

maiden fable
#

Why tho

vale wing
#

Self required

maiden fable
#

U were using a loop before too tho

vale wing
#

Ik I can move it out but still

maiden fable
#

Wym self required?

vale wing
#

Um what loop

vale wing
maiden fable
#

why

vale wing
#

Which requires the object reference which is self if my english is normal

maiden fable
#

Ok so I'm confused rn ngl. @patent lark mind coming over here? Lol

patent lark
#

whats up?

maiden fable
#

@vale wing needs help

vale wing
#

The whole construction is this

class UserView(View):
    def __init__(self, user_id: int, timeout: int = 180):
        super().__init__(timeout=timeout)
        self.result = None
        self.user_id = user_id

    async def interaction_check(self, inter: Interaction):
        return inter.user.id == self.user_id

    async def on_timeout(self):
        raise TimeoutError

    async def get_result(self, message: Optional[Message]):
        await self.wait()
        self.disable_buttons()
        if message:
            await message.edit(view=self)

        return self.result

    def disable_buttons(self):
        for button in self.children:
            if isinstance(button, Button):
                button.disabled = True

class NumericView(UserView):
    def __init__(self, user_id, labels: 'list[str]', timeout: int = 180):
        super().__init__(user_id, timeout=timeout)
        for label in labels:
            self.add_item(NumberButton(label))

class NumberButton(Button):
    def __init__(self, label):
        super().__init__(label=label, style=ButtonStyle.gray)

    async def callback(self, _):
        view: NumericView = self.view
        view.result = self.label```
patent lark
#

and the issue is?

vale wing
#

It takes ages for button to give response

cloud dawn
#

Cavalry has been called.

manic wing
#

salute

maiden fable
#

Yes

#

@cloud dawn's help is needed

manic wing
#

cavalry arrives: no help given

vale wing
#

Maybe I need to stop the view?

slate swan
#

!d discord.ui.View.children

unkempt canyonBOT
sage otter
#

look at all those smart people flooding in. couldn’t relate.

slate swan
#

you can use .disabled = True , on all of them to disabled the view

vale wing
#

dpy 2.0

slate swan
#

Seems like dpy

vale wing
maiden fable
vale wing
#

Ima try to stop the view in callback

vale wing
#

Wow it did that lmao

#

Now I have another issue tho

#
class PageView(UserView):
    def __init__(self, user_id, timeout: int = 180):
        super().__init__(user_id, timeout=timeout)

    @button(label='Previous', style=ButtonStyle.gray, disabled=True, emoji='⬅️')
    async def previous_page(self, *_):
        self.result = 'previous'
        self.stop()

    @button(label='Next', style=ButtonStyle.gray, emoji='➡️')
    async def next_page(self, *_):
        self.result = 'next'
        self.stop()

    @button(label='Exit', style=ButtonStyle.danger)
    async def next_page(self, *_):
        self.result = 'exit'
        self.stop()```
But for some reason `Next` button is not displaying
cloud dawn
tawdry perch
#

is client secret same thing as token?

cloud dawn
tawdry perch
#

what do I fill on them?

cloud dawn
tawdry perch
#

smth I need to request?

wicked atlas
tawdry perch
#

ah I see, thx!

vale wing
cloud dawn
maiden fable
#

Wym @vale wing

#

It shows only the first 2 buttons?

vale wing
slate swan
#

it comes in the order you add_item to the view

vale wing
#

Why are there 2 of them but I added 3 in code

maiden fable
#

Try printing self.chlidren

tawdry perch
#

how do I get a OAuth2 URL?

vale wing
#

Nvm I just named 2 functions the same

#

How dumb am I

maiden fable
#

Lol

ebon island
#

If I save a discord.member.Member object to an attribute within a local Object can I call the mention method on that somehow?

jagged root
#

how can i do so async def on_message only work if 3 arguments are given

fluid spindle
#

Hi... So I'm trying to make a thread that keeps checking the time, but it's not working like a thread should work. The bot doesn't respond until the sendTime is reached. Is there something that I'm missing here?

maiden fable
jagged root
ebon island
#

so obviously this isn't real code but it shows the assignment, imagine a given ctx as the source so it wouldn't be a static assignment

@dataclass
class User:
  user_object = ctx.author

Can I somehow access the ctx.author.mention method from the original ctx.author instance?

maiden fable
fluid spindle
jagged root
#

ok

maiden fable
fluid spindle
maiden fable
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
jagged root
sage otter
#

yes. I’m not sure what you're confused about.

sage otter
#

Like what are your intentions with whatever that is.

fluid spindle
jagged root
fluid spindle
sage otter
#

Or use the commands framework and not try to reinvent the wheel

fluid spindle
jagged root
#

hm

#

k

honest vessel
#

also if you just wanna split 1 word, u can do msg.split(" ", 1)

jagged root
#

kk

dim otter
#

Hii
How you get the server icon ? (ping me with responding)

slate swan
#

-> Don't use threading with asyncio
-> Use a task instead of a while loop

final iron
#

He shouldn't be using threading

slate swan
#

Guys, How do I send a confirmation message again here, like when I do when send_message it doesnt let me send another message ;-;

@disnake.ui.button(label="", style=disnake.ButtonStyle.red)
    async def valo_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        await interaction.response.send_message(content="", ephemeral=True)
        res = await check_for_authors_msg(interaction.channel_id, interaction.author)
        try:
            await db.add_data(interaction.author, res)
            #Send another message after this         
        except: pass
craggy cloak
#

How can i humanize this?

total_amount = users[user]["wallet"] + users[user]["bank"]

craggy cloak
#

humanize.intcomma

final iron
#

There's a built in thing for that

pliant gulch
unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

10,000
boreal ravine
#

!d disnake.Interaction.followup could use this

unkempt canyonBOT
boreal ravine
slate swan
slate swan
#

does anyone know how to give people with ranks different cooldowns?

ebon island
#

probably setting up a method that checks their rank and returns an integer

#

at least that's my instinct on that

cloud dawn
#

Well we help with code not heroku

plain cloud
#

me and heroku 🤜🤜🤜 never again

slate swan
#

I want to make a kick command but I always fail. Can someone send me a code for this?

sage otter
#

No, but what you could do instead of taking other peoples stuff is send us yours and have us help you with it.

zenith basin
#

Can any one help me

slate swan
#

Here it is

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
        await member.kick(reason=reason)
        await ctx.send(f'User {member.mention} has been kick')```
sage otter
#

Remove self. You're not in a cog.

slate swan
#

Didn't work

sage otter
#

I mean, what’s the error.

slate swan
#

Missing permissions but I'm the admin

sage otter
#

Is it 403 ?

slate swan
#

Yes

#

403 Forbidden

lusty swallow
#

Oof

sage otter
#

So your bot doesn’t have permissions then.

slate swan
#

Hm

#

Lemme check

lusty swallow
#

What line does it raise the error?

#

If the bot is not an admin, it can't see private channels. That might also be the case

slate swan
lusty swallow
#

Can you paste traceback?

#

Might be a different error

pulsar shell
# fluid spindle Hi... So I'm trying to make a thread that keeps checking the time, but it's not ...

It seems like you’re trying to send a message after a specific amount of time, you can simply use asyncio.sleep or loop.call_later with the delay e.g.

await asyncio.sleep(…)
await ctx.send(sendData['text'])

OR

ctx.bot.loop.call_later(…, ctx.bot.loop.create_task, ctx.send(sendData['text']))

you should probably be using the first one unless you don’t want to wait for the message to be sent

zenith basin
jaunty wraith
#

Anyone know whats wrong with my code? I cant work it out

cloud dawn
sage otter
#

Oh yeah, that would probably be the reason then.

zenith basin
lusty swallow
cloud dawn
lusty swallow
zenith basin
honest vessel
silver iris
#

Hey please can I have some help I have my discord bot connected to my site how do I make it so when they connect they get a certain role in my discord

cloud dawn
lusty swallow
jaunty wraith
honest vessel
#

@jaunty wraithhttps://www.w3schools.com/python/gloss_python_indentation.asp

silver iris
lusty swallow
silver iris
#

Let me explain it better lol

lusty swallow
silver iris
#

Is they away to make add the role when you connect to the site though I believe it is possible I’m just not entirely sure

#

Hmmm thank you !

slate swan
#

Someone know how to solve it?

#

does anyone know how to add an "Add to your server" button in a discord bot?

slate swan
#

aka in the dev portal

#

ok

slate swan
slate swan
slate swan
silver iris
#

Hi does anyone know if I can use my discord bot via aws server etc cloud functions

slate swan
#

i can't find it

silver iris
#

Amazon servers

slate swan
#

sorry, no idea

manic wing
slate swan
cloud dawn
#

What are we protesting about?

manic wing
#

the fact that we all arent admin

#

its brutally unfair and quite frankly descriminatory

slate swan
#

why it's unfair?

#

admins and mods may be busy and helping each other is good

cloud dawn
slate swan
#

also this button is only for verified bots?

cloud dawn
#

Hard to miss

silver iris
cloud dawn
sick birch
#

I've tried with EC2 before and it worked well for my needs

silver iris
#

@sick birch hey thank you man! Do you know how I would go about doing it?

slate swan
cloud dawn
sick birch
slate swan
sick birch
#

You can install Python on it (probably has it already) and just run your file as if you were going to do it from your local machine

slate swan
#

OAuth2?

sick birch
#

Preferably you can put linux on it

silver iris
#

It’s how you connect your discord account with your own website

silver iris
cloud dawn
# slate swan in rich presence?

OAuth2>General>Default Authorization Link>AUTHORIZATION METHOD>Custom URL>In-app Authorization

Check both bot and applications.commands
Then the permission your bot needs

sick birch
# silver iris Thanks man

Btw they let you SSH into it so it's almost as if you had physical access to it, i suppose you know how VPS work already so it shouldn't be an issue for you haha

slate swan
cloud dawn
#

😂

slate swan
#

true : D

cloud dawn
#

Nah np it's not shown as good as they could have done.

slate swan
#

i'm new to python and generally at bots

#

How can you use the new discord mute thing in your discord bot for more automation

fluid spindle
#

Just out of curiosity, does Discord allow you to see who has read your message? I'm thinking it doesn't...

slate swan
#

No

jaunty wraith
slate swan
jaunty wraith
slate swan
#

Mute role hardly makes any sense anymore

slate swan
jaunty wraith
#

Yea

#

I think i imported disnake at one point to use / commands but it didnt work

slate swan
jaunty wraith
slate swan
glacial kernel
#

I'm making a ticket bot and in the part of closing the ticket I would like this command to only be executed when in a ticket room.
Does anyone know how?

vale wing
slate swan
#

im just gonna use disnake

vale wing
glacial kernel
#

Yes

#

Do you know how?

vale wing
#

You could create a check, depends on your code structure and data storage

#

The most simple check is

def some_check(ctx):
    return ctx.channel.id == 123456789

@bot.command()
@commands.check(some_check)
async def your_command(): ...```
#

I hope I remember it correctly lol

glacial kernel
#

I can take a screenshot of this part of my code and you see what I can do

vale wing
#

Ok

glacial kernel
#

I had a problem taking the screenshot so I took a picture @vale wing

unkempt saddle
#

Can someone help me with how to make the bot ignore a specific user if they type out a special command

for example if the user write $stop the bot completely ignores the user and if the user types $start the bot listens to the users commands again?

vale wing
slate swan
slate swan
slate swan
slate swan
vale wing
glacial kernel
vale wing
slate swan
glacial kernel
vale wing
#

Not really lol, but I suppose yours is

glacial kernel
#

Yes

#

true

vale wing
#

You could just check if the channel is in your category

def ticket_check(ctx):
    return ctx.channel.category.id == tickets_category_id```
glacial kernel
#

How do I implement this in the middle of my code?

vale wing
#
def ticket_check(ctx):
    return ctx.channel.category.id == tickets_category_id

@bot.command()
@commands.check(ticket_check)
async def FecharTicket(ctx): ...```
jaunty wraith
#

Can anyone tell me what the problem is with this i want it so you do the command and if the 2nd arg (message) = none then the bot will respond but it doesnt work

glacial kernel
#

Thank you bro

vale wing
#

The check function and the check decorator

#

Np

vale wing
#

You could set a default value or provide typing.Optional typehint

jaunty wraith
vale wing
#

I understand what happens

jaunty wraith
vale wing
#
async def mcfind(ctx, message = None): ...

#alternative way with Optional
async def mcfind(ctx, message: Optional[str]): ...```
#

Not sure if you need str in optional but lemme check that

jaunty wraith
#

Thank you

#

Ok

boreal ravine
#

typehinting to the optional class doesnt make the param optional

#

you gotta set a value to the param to make it optional

vale wing
#

In terms of python overall it doesn't I agree

#

Btw is this considered normal practice or there's a better way to make requests to discord API inside a bot?

async with aiohttp.ClientSession(headers={'Content-Type': 'application/json', 'Authorization': 'Bot token') as session:
    await session.patch(f'https://discord.com/api/v9/guilds/123/members/123', json=...)
   ...```
wicked atlas
#

Session encapsulates a connection pool (connector instance) and supports keepalives by default. Unless you are connecting to a large, unknown number of different servers over the lifetime of your application, it is suggested you use a single session for the lifetime of your application to benefit from connection pooling. (aiohttp docs)

jaunty wraith
mild tree
#

Traceback (most recent call last)

#

hi have this

#

problem

#

how to fix them?

patent lark
#

..

vale wing
wicked atlas
mild tree
#

but i dont have it, this is problem

jaunty wraith
#

Screenshot the full console

mild tree
#

the window closes after a second

#

the text flashes very quickly and closes

vale wing
#

You must be running the file just by clicking on it?

#

Or I got you wrong

jaunty wraith
wicked atlas
mild tree
#

I don't have a hosting bot connected and so far I'm testing the script by opening it in cmd

soft lynx
#
... # the rest of the cmd is up here
elif args == "North America" or args == "NA23":
      role_ids : list = dictionary ["north-america"]
      await ctx.send(",".join([ctx.guild.get_role(role_id).name for role_id in role_ids if len(ctx.guild.get_role(role_id).members) < 0]))

i want my bot to send every role within a dictionary that users do not currently have. Right now, its sending every role whether or not someone has it.

Here is the dictionary:

 # north-america; Canada, USA, Mexico
    dictionary = { 
      "north-america": [924737989341503609, 924737988800438322, 924737997503627265]
    }

Does anyone know how I can make my bot send each role in the above dictionary that no users currently possess?

vale wing
#

Or I can use it without with

mild tree
#

it's a new bug for me and I don't know what to do with it, that's why I went here: //

slate swan
supple plover
#

hi
today i learned the fact that discord.py died
and now (I know that probably that question was asked a billion times but..) I am really confused with a bunch of forks that has emerged from the corpse of discord.py

disnake vs nextcord vs pycord what's the difference and what you use if you are coding a bots for discord?

vale wing
#

Lol had the same issue today

wicked atlas
mild tree
#

i dont have this

vale wing
wicked atlas
#

Whichever one you use is up to you really. I like disnake

supple plover
#

what is less buggy are most interested into aha

#

just because the basic fear that they are new libs with low stability

mild tree
#

maybe its code problem... can i send it on dm?

vale wing
#

Yeah

soft lynx
vale wing
soft lynx
vale wing
#

Probably because of attempts to send an empty string

soft lynx
#

is there a different way to go about what im trying to do? ive been reccomended to use the utils, or iterate

vale wing
#

So you need to get roles that have 0 members right?

slate swan
#

how can I keep my bot up 24/7 ?

vale wing
#

I would do it like this

roles_ids = [...] #however you get them
roles = [ctx.guild.get_role(i) for i in roles_ids]
roles_string = ", ".join([role.name for role in roles if len(role.members) == 0])
vale wing
#

You could also filter roles

vale wing
# slate swan free?

I don't know much, but some people use heroku and replit, although it is not recommended

#

Don't ask me how

slate swan
#

can u tell me if this is a good enough deal to run my bot?

vale wing
#

?

slate swan
#

Chassis model
Dell DSS5100

Processor
1× Intel® C2350 (Avoton)

CPU - 2C/2T - 1.7 GHz

Storage
1 × 1 TB SATA

Memory
4 GB DDR3

#

is that good enough

#

and its for 13 euro

vale wing
#

Way too powerful for an average bot but it depends on your bot lol

slate swan
vale wing
#

Try galaxygate

#

They have servers for 3$/mo

#

I host all my bots there, works fine

slate swan
#

Ok thx

#

wait will it work for europe?

vale wing
#

And yeah you may have some issues regarding running bot script on VPS feel free to ask me then

vale wing
slate swan
#

ok so what option shoudl I go for?

#

1 gig or 2 gig

vale wing
#

To start with, does your bot require many resources?

#

Like mine is at > 100 guilds and it doesn't need more than 300 Mb I think

slate swan
vale wing
#

Take the cheapest version

slate swan
slate swan
slate swan
vale wing
#

Ok

jaunty wraith
#

Right?

vale wing
#

Just saying there's a faster way to check if argument is not None

if not arg: #same with if arg == None```
slate swan
#

antib = {}

@bot.command()
@commands.has_permissions(ban_members = True)
async def on(ctx):
antibots = antib.get(ctx.guild.id, False)
if antibots == False:
antibots[ctx.guild.id] = True
await ctx.send("Ok")

#

im having the following error :

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'bool' object does not support item assignment

slate swan
#

can somene help me ?

pliant gulch
vale wing
#

Yeah

pliant gulch
#

The best way, and pythonic way to check if someone is None is by using is, E.g arg is not None

vale wing
#

Afaik is is basically == but it also checks if the objects take the same place in memory

slate swan
vale wing
#

You are trying to assign an item to a bool object

vale wing
#

Your dictionary is antib and not antibots right?

thin kelp
slate swan
#

yes

pliant gulch
slate swan
#

can i send a link ?

vale wing
#

Depends what link

slate swan
#

stakoverflow

vale wing
#

I think you can

slate swan
#

my english is so bad, sorry

#

its something like that what i need

#

but it is not working

thin kelp
slate swan
#

yes

#

and didnt work

vale wing
#

You should just name the variables in a comfortable and logical way for you

vale wing
vale wing
#

Np, I hope I helped

slate swan
#

but, give a second

#

@bot.event
async def on_member_join(member):
global antimalicius
global antib
if antimalicius == True:
file = open('blacklist.txt', 'r')
members_banned = file.readlines()
if str(member.id) not in members_banned:
pass
else:
await member.ban()

if antib == True:
    if not member.bot:
        pass

    else:
        await member.ban()

else:
#

the on command works, but when i add a bot, its not banned

#

dont pay attencion on the blacklist part

vale wing
#

!code

unkempt canyonBOT
#

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.

pliant gulch
vale wing
#

Yeah but it would iterate more roles

vale wing
slate swan
#

alr

pliant gulch
#

get_role already iterates through the roles

tawdry perch
#

How do I get Oauth url for my bot?

vale wing
#

Didn't know

vale wing
tawdry perch
#

Ye

slate swan
#

@bot.event
async def on_member_join(member):
    global antimalicius
    global antib
    if antimalicius == True:
        file = open('blacklist.txt', 'r')
        members_banned = file.readlines()
        if str(member.id) not in members_banned:
            pass
        else:
            await member.ban()

    if antib == True:
        if not member.bot:
            pass

        else:
            await member.ban()

   
thin kelp
#

Wait

#

Isn't antib a dictionary

vale wing
#

This looks uh weird

slate swan
#

know

thin kelp
#

The problem is in the antib == True part I think

vale wing
#

This thing would just ban bot accounts on join if antib is enabled

slate swan
#

yes

vale wing
#

And where is antib defined?

thin kelp
#

Get the guild id and try antib[guildid] == True

vale wing
#

Is it supposed to be a dictionary or a boolean? 9839megaflushed

slate swan
#

i mixed lot of code

#

i will send you the originsl code

#

1 sec

vale wing
#

Understandable

pliant gulch
#

Making getitem O(1)

vale wing
#

Oh lol

pliant gulch
#

I was mistaking get_role with how utils.get works

slate swan
#

would this work

await ctx.send(random.choice(options.split(",")))

?

pliant gulch
#

yes

vale wing
#

If options isn't an empty string yes

slate swan
#

yeah it is

#

antib = False
antimalicious = False



@bot.command()
@commands.has_permissions(ban_members = True)
async def on(ctx):
    global antimalicius
    global antib
 
    try:

        antimalicius = True
        antiflood = True
        antib = True
        antiads = True
        await ctx.send(":emoji_33: | Proteccion Automatica Activada")

    except:
        await ctx.send("Este comando solo puede ser usado por mi Creador y Staffs")


vale wing
#

Format it

slate swan
#

there is

#

ok

slate swan
jaunty wraith
#

@slate swan

slate swan
#

that is

vale wing
vale wing
slate swan
#

several

slate swan
jaunty wraith
vale wing
abstract pecan
jaunty wraith
jaunty wraith
abstract pecan
jaunty wraith
#

Im coding it on replit yea

abstract pecan
final iron
#

How much would I need to know about SQL before I can use it as a db for my bot? I'm currently using SQLBolt to learn and I'm on Outer Joins but I don't really think ill need to know those

jaunty wraith
vale wing
#

If you don't provide an argument it will raise an exception, you can handle it however you would like to

abstract pecan
slate swan
jaunty wraith
#

@slate swan knows what im on about

abstract pecan
slate swan
#

yea

vale wing
final iron
vale wing
#

@slate swan I will help you please wait

final iron
tawdry perch
#

Same thing, and a good choice

final iron
#

I am aware

vale wing
#

Asynchronous sqlite? zyeaok

tawdry perch
#

Ye

vale wing
#

Interesting

#

I should look at it lol

final iron
#

I just need to learn how to create the file and frame

tawdry perch
#

!pypi aiosqlite

vale wing
#

Maybe it is better than common sqlite3

unkempt canyonBOT
final iron
#

I also need to implement it in code

tawdry perch
#

It will be quite easy

vale wing
#

As I looked nothing very complicated just full of awaits huh

slate swan
#

tthank you, i never used a database

final iron
#

It might sound strange but is there any file structure I would want?

#

Like the way my files for the bot are organized?

#

I'm planning on publishing the finished project to Github

pliant gulch
#

You'd want the core and the cogs to be seperated at least

#

Perferably all in a root folder as well

#

Conventionally called src most of the time

#

Or depending on what conventions you follow

vale wing
#

@slate swan so to make individual config for every guild, at the beginning stage I would just recommend to use a dictionary

guilds_config = {}

We can provide an example guild

guilds_config[123] = {
    "antibot": True,
    "antispam": False
}```
You can make that dictionary whatever you want

Next, to check some data, you can do like
```py
antibot_enabled = guilds_config[guild_id]['antibot']```
And operate with it
slate swan
#

.json file ?

vale wing
slate swan
vale wing
slate swan
final iron
pliant gulch
pliant gulch
vale wing
#

Mistaken

pliant gulch
#

Like the actual subclass itself if you extend or whatnot

slate swan
#

guilds_config = {}
guilds_config[123] = {
"antibot": True,
"antispam": False
}

#

into a json file

#

error xd

#

expecting a json objetc or array

#

@vale wing

vale wing
#

!d json

unkempt canyonBOT
slate swan
#

a?

#

what?

#

@vale wing

sick birch
#

!e

test = {}
test[1] = 1
print(test)
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

{1: 1}
sick birch
#

mm i suppose not

zenith basin
pliant gulch
#

The eval is evaluating python code which can have int keys

#

If you write inside of a json file it will scream

sick birch
#

Ah that's what I was thinking of

slate swan
#

but

#

what im doing bad

sick birch
#

Also obligatory: you should consider using a proper database rather than a JSON file

ebon island
#

How do I get a Discord bot to join a voice Channel and not leave unless it is commanded to do so?

unkempt canyonBOT
#

@coral pelican Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

sage otter
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
slate swan
ebon island
#

It keeps leaving after a certain amount of time when nothing is playing rather than just sitting in the voice Channel as intended

potent spear
full lily
#

Does anyone know of a way to use a local image inside of an embed? The implementation I have now sends the image outside of the embed

file = discord.File("test_image.png")
embed.set_image(url="attachment://image.png")
await self.ctx.send(file=file, embed=embed))
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

slate swan
#

your method is correct , except for the url must be attachment://test_image.png in the set_image

heavy folio
#

^

ebon island
torn sail
ebon island
#

ooh I see there is a timeout arg, maybe 0 or None?

potent spear
ebon island
#

I'm testing doing .connect(timeout=None) and it might be the answer

#

default is 60

potent spear
#

I don't think it auto disconnects, you can set it to 5 secs and check...

ebon island
#

yeah, it did when I checked

#

disconnected after about a minute inactive

#

which is consistent with the default arg of 60

potent spear
#

yeah, all good, even if the bot is playing something?

ebon island
#

it isn't playing anything haha, I am sure it would stay if it were playing something

potent spear
#

well, that's where you need the other method

ebon island
#

timeout=None seems to have done it

potent spear
#

it's useless for a bot to keep playing a playlist of an hour if no-one is listening 🧠

ebon island
#

haha not entirely useless

potent spear
#

it sure as hell is imo

ebon island
#

24/7 cipher channels for freestyle rap are a use case where you want it on and in a voice channel no matter what so people can join at any time and immediately jump in

potent spear
#

yeah, 24/7 channels are different, but I was talking about "normal" music bots

ebon island
#

haha yeah

#

right now it's not even a music bot

#

it's a freestyle practice tool

#

so it does things like word generation

#

eventually we'd like to make it play music and such

#

we'll have a playlist of instrumentals produced by friends of the BarHub and shout their channels etc out every time a song is played

pliant gulch
#

Neat idea, haven't heard of a freestyle practice bot

ebon island
#

haha yeah, we're leading the charge on that front

#

we're already in some of the largest servers even in the scuffed af implementation it had previously

#

the build I have on my dev rig is about 1000x better than the live build

#

I had a hilarious message to our group chat where I said What?? We have a working STOP COMMAND?!?! haha and genuinely that was an accomplishment

#

the build that was up the stop command was finnicky at best

#

now it is rock solid

#

dead stop as soon as the command is given

#

eventually we will have things like scoring and leaderboards

#

and gamification elements to make it competitive and reward participation

#

plus a front end web page that you can use separately

#

also confirmed, it is still sitting in the voice channel so it looks like timeout=None was exactly the fix 😄

full lily
ebon island
#

What is the best way to call disconnect?

full lily
#

thanks for the reply though

ebon island
#

How do I get the instance of the bot? So like, to check if it is in a server for example

#

or I guess another question, how do I get the instance of the VoiceClient connection once channel.connect() is performed?

#

think I got it actually

#

looked the docs and it returns a voice client I guess

#

so I am going to try and write it to a variable and see if I can then call methods on that variable

slate swan
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
slate swan
#

Use this for everg object which had permissions and set the perms to None

#

As overwrite=None

full lily
slate swan
#

pleasure

grand shell
#

hey! i have the id of a channel. how can i get the channel object from it?

grand shell
#

thanks :))

slate swan
#

yw

grand shell
#

how can i get the guild from an id?

#

i dont rlly have access to the client because its in a cog

slate swan
#
bot.get_guild(int)
grand shell
#

you mean self.bot?

#

it returns None for me idky

slate swan
#

show your cog

grand shell
#

its quite big..

slate swan
#

your init dunder

grand shell
#
class SelfAdvertise(commands.Cog):

    def __init__(self, client):
        self.client = client
slate swan
#

typehint client to commands.Bot

grand shell
#

wdym?

slate swan
#
 def __init__(self, client: commands.Bot):
        self.client = client
grand shell
#

hmm

#

it still returns None

#
@tasks.loop(seconds = 10)
    async def ad_loop(self):
        adIDs = self.get_advertising_ids()

        for id in adIDs:
            chanID = self.get_chanID(id)

            serv = self.client.get_guild(id)
            chan = serv.get_channel(chanID)

            print(serv)
            print(chan)
#

this gives me an error

#

'NoneType' object has no attribute 'get_channel'

sage otter
#

self.client isn’t returning None.

#

get_guild() is returning None.

slate swan
#

What does the sudo command do

#

#unix , and it means superuser command

sick birch
slate swan
#

No... some bots have the sudo command

#

hm?

sick birch
#

Huh

sage otter
#

Executes a command while bypassing it’s checks.

slate swan
#

any example/ context

#

Someone said it runs the command with bot owner privileges

sick birch
#

Sudo usually means doing something as someone else

slate swan
slate swan
sage otter
#

yeah

slate swan
#

Ok

#

How do I make that command

sage otter
#

most people use Context.invoke() which bypasses checks.

slate swan
#

Oh

slate swan
sage otter
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
slate swan
#

I have seen other people do !sudo @slate swan ping

sage otter
#

That’s a mock command

slate swan
#

What do you mean?

sage otter
#

It invokes the command under a certain user instead of yourself.

lament mesa
slate swan
sage otter
#

I mean if you make it that way, yeah.

slate swan
#

Do you recommend having a sudo command?

slate swan
#

In this case it was the guild

lament mesa
#

nope, it doesn't affect runtime

slate swan
#

in normal instances yes

sage otter
slate swan
#

Ok

#

but dpy converts things with type hinting

lament mesa
#

dpy only does typehint conversion in commands, not in cogs

slate swan
#

which is very unpythonic

sick birch
# slate swan Ok

There's an excellent module called jishaku that already does "sudo" for you, amongst many other features such as running code in the terminal of the machine being hosted in, viewing files on the local machine, and running arbitrary code. I know that sounds very insecure but it's only limited to the bot owner, and is useful for debugging

sage otter
#

Probably the most useful discord.py related module out there tbh.

midnight mica
#

I am making a discord bot

#

It has less features by now

#

As suggested replit can't be used for mass communication bots, so any other platforms? and I want to connect it through uptimerobot as well if your telling a platform. Please.

slate swan
#

@sage otter
@client.command()
async def sudo(ctx, *, command):
await ctx.invoke(command)