#discord-bots

1 messages ยท Page 930 of 1

brazen raft
#

Always do discord stuff inside discord stuff

slate swan
#
@bot.command()
async def servers(ctx):
   await ctx.send("\n".join(guild.name for guild in bot.guilds))
abstract kindle
#

I'm trying this, but it's telling me collection = await db.connect() needs to be in a function because its being awaited

#

Where am I supposed to put it?

brazen raft
#

It needs to be used inside an asynchronous function

abstract kindle
#

yeah

brazen raft
#

What's db btw

slate swan
#

Can we get guild owner ?

quick gust
#

you can

brazen raft
quick gust
#

.owner attribute or .owner_id if u want the owner's ID

slate swan
#

Ok ๐Ÿ‘

abstract kindle
#

the python package

#

.collect() is a function in the connection.py file in the db package

slate swan
#

Why are there two people spamming my dms for help

#

??

#

Who?

cosmic agate
#

hmm ok it doesnt work if its outside

abstract kindle
#

and .collect() is supposed to be returning database['users'], but I'm having a hard time

brazen raft
junior verge
#

Uhm, this is my requirements:

matplotlib==3.5.1
matplotlib-inline==0.1.3
mpmath==1.2.1
numpy==1.22.0
py==1.11.0
pymongo==4.0.1
requests==2.27.1
discord==1.7.3
discord.py==1.7.3
aiohttp==3.7.4
async-timeout==3.0.1
discordmongopy==0.3.0
motor==2.5.1
pymongo==4.0.1
``` Got no clue what to change
brazen raft
abstract kindle
#

typo

slate swan
unkempt canyonBOT
brazen raft
#

Custom discord clients are illegal

slate swan
#

Bot client?

brazen raft
#

Doesn't matter how

slate swan
#

..

#

Sad

tough lance
#

What's sad about it tho.

abstract kindle
#

I am so lost

slate swan
#

R.I.P

cloud dawn
abstract kindle
#

This all started as me trying to remove my duplicate code and I've wasted 3 hours trying to figure out how do do what I could already do before

cloud dawn
#

Oh you mean like betterdc stuff

slate swan
junior verge
#
client.db = client.mongo["example"]
``` Hm?
abstract kindle
#

I suppose

cloud dawn
abstract kindle
#

I use a JSON file to store the url to connect to my MongoDB

#

and I connect to it using this code

    data = json.load(file)

cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']```
junior verge
cloud dawn
abstract kindle
#

But I have this code in each of my cogs, and PyCharm didn't like that, so I was wondering if I should remove the duplicates and how I would do so

junior verge
abstract kindle
#

@junior verge mongo and motor are 2 different things, don't use both at the same time

brisk zodiac
#
@client.event
async def on_member_join(member):
    guild = member.guild
    channel = guild.get_channel(955726308787245086)
    await channel.send(f"{member.mention} has just joined the server!")

@client.event
async def on_message(message):
    suggestionData = '{}'.format(message.content).replace('!suggest', ' ')
    if message.author == client.user:
        return
      
    if message.content.startswith('!suggest'):
        embed=discord.Embed(title = 'New Suggestion')
        embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
        channel=client.get_channel(955726308787245086)
        embed.color=random.choice(color)
        embed.set_footer(text='Suggested by ' + message.author.name, icon_url=message.author.avatar_url)
        up_emoji = '\N{THUMBS UP SIGN}'
        down_emoji = '\N{THUMBS DOWN SIGN}'
        msg = await channel.send(embed=embed)
        await msg.add_reaction(up_emoji)
        await msg.add_reaction(down_emoji)
        await message.channel.send('Your suggestion has been submitted ' + '**' + message.author.name + '**')

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

client.run(os.getenv('TOKEN'))```How can i add cooldowns here? I"m still figuring out about it
junior verge
#

Ah typo xD

abstract kindle
#

It does work, but it's in each of my cogs

junior verge
#

Sorry my bad

abstract kindle
#

and PyCharm doesn't like that its duplicate

cloud dawn
abstract kindle
#

So I was wondering if I should get rid of the duplicates. Would that be more pythonic?

cloud dawn
abstract kindle
#

What does that mean?

#

I was told to make a db package with an init.py file and a connection.py file

#

And I stored

    data = json.load(file)

cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']``` this in the connections.py file
cloud dawn
placid skiff
#

bot.db = your_database

abstract kindle
#

I see

#

Would I then be able to run this? result = bot.db.find_one({"_id": ctx.author.id})

placid skiff
#

yup

cloud dawn
junior verge
#

Getting this error now

client = commands.Bot(command_prefix=get_prefix, help_command=None)
``` I defined get_prefix
```py
async def get_prefix(client, message):
    if not message.guild:
        return commands.when_mentioned_or()

    try:
        data = await client.prefixes.find(message.guild.id)

        if not data or "prefix" not in data:
            return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
        return commands.when_mentioned_or(data["prefix"])(client, message)
    except:
        return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
abstract kindle
#

So how would I go about overriding the bot class? This is stuff I haven't done before

cloud dawn
abstract kindle
#

Oh

cloud dawn
#

Does look nicer though, do recommend checking it out as a learning experience.

abstract kindle
#

Okay, I'm just trying to make it so I don't have

    data = json.load(file)

cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']``` at the top of every cog
velvet tinsel
#

Ok

brisk zodiac
#
@client.event
async def on_member_join(member):
    guild = member.guild
    channel = guild.get_channel(955726308787245086)
    await channel.send(f"{member.mention} has just joined the server!")

@client.event
async def on_message(message):
    suggestionData = '{}'.format(message.content).replace('!suggest', ' ')
    if message.author == client.user:
        return
      
    if message.content.startswith('!suggest'):
        embed=discord.Embed(title = 'New Suggestion')
        embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
        channel=client.get_channel(955726308787245086)
        embed.color=random.choice(color)
        embed.set_footer(text='Suggested by ' + message.author.name, icon_url=message.author.avatar_url)
        up_emoji = '\N{THUMBS UP SIGN}'
        down_emoji = '\N{THUMBS DOWN SIGN}'
        msg = await channel.send(embed=embed)
        await msg.add_reaction(up_emoji)
        await msg.add_reaction(down_emoji)
        await message.channel.send('Your suggestion has been submitted ' + '**' + message.author.name + '**')

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

client.run(os.getenv('TOKEN'))```
How can i add cooldowns here? I"m still figuring out about
abstract kindle
#

Cooldowns for what?

brisk zodiac
abstract kindle
#

I don't see any command

#

I see 3 events

brisk zodiac
#

for the event

#

the second event

abstract kindle
#

You can't add an event for a cooldown?

#

Oh i see... you have your 'commands' in a weird way

cloud dawn
abstract kindle
#

A command looks like this @bot.command() async def get_commands(ctx, cog): commands = get_commands(f"Cogs.{cog}") await ctx.send(commands)

slate swan
junior verge
abstract kindle
#

You have the command decorator, and then the name of the function is the command, and you just put the prefix you assigned to your bot in front of it

cloud dawn
junior verge
#

Yeah it gives that error

abstract kindle
#

You don't have any commands to add cooldowns to

#

You have your bot recognizing when someone types !suggest

slate swan
#

My button not working after bot restart how to fix

abstract kindle
#

That is not a command, that's the bot looking for a specific message

abstract kindle
#

change your suggest command

slate swan
#

hey

#

peeps

#

Guys thats possible to make the bot read a DM and send in in webhook?

#

so ho

abstract kindle
#
@client.command()
async def suggest(ctx):
    embed=discord.Embed(title = 'New Suggestion')
        embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
        channel=client.get_channel(955726308787245086)
        embed.color=random.choice(color)
        embed.set_footer(text='Suggested by ' + ctx.author.name, icon_url=message.author.avatar_url)
        up_emoji = '\N{THUMBS UP SIGN}'
        down_emoji = '\N{THUMBS DOWN SIGN}'
        msg = await channel.send(embed=embed)
        await msg.add_reaction(up_emoji)
        await msg.add_reaction(down_emoji)
        await ctx.send('Your suggestion has been submitted ' + '**' + message.author.name + '**')```
#

Something like this @brisk zodiac

slate swan
#

how do i make my botghost thing not say "MADE BY BOT GHOST"

abstract kindle
#

ooops

brisk zodiac
abstract kindle
#

@commands.cooldown(1, 86400, commands.BucketType.user) use this decorator

brisk zodiac
#

Where?

abstract kindle
#

It's a decorator, so it goes above the command

#

Your @client.events are all decorators

cloud dawn
abstract kindle
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

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

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.
abstract kindle
#

@brisk zodiac

brisk zodiac
#

okay

junior verge
# cloud dawn `return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)` this part re...

I changed it to, ```py
async def get_prefix(client, message):
if not message.guild:
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)

try:
    data = await client.prefixes.find(message.guild.id)

    if not data or "prefix" not in data:
        return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
    return commands.when_mentioned_or(data["prefix"])(client, message)
except:
    return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
brisk zodiac
#

It said this

cloud dawn
junior verge
#

In my config file too?

slate swan
cloud dawn
# junior verge Sure, where?
async def get_prefix(client, message):
    if not message.guild:
        return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)

    try:
        data = await client.prefixes.find(message.guild.id)

        if not data or "prefix" not in data:
            print("1")
            return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
        print("2")
        return commands.when_mentioned_or(data["prefix"])(client, message)
    except:
        print("3")
        return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
abstract kindle
#

That's basic python man

junior verge
#

okay

abstract kindle
#

You gotta spend a little more time learnin about that

junior verge
#

me?

abstract kindle
#

No no

junior verge
#

ah okay

abstract kindle
#

The other guy lol. Had an indentation error and asked about it

junior verge
#

lol

zealous dagger
#

Hey guys

#

I want help

cloud dawn
abstract kindle
#

Lmfao no

abstract kindle
#

Not at all but I can try

junior verge
#

Only makes it through 1

slate swan
abstract kindle
#

You guys are way better. Also I figured it out Panda

pliant gulch
junior verge
#

Wait

#

I think I know it

zealous dagger
#

Selects and dropdown

cloud dawn
# junior verge

Thought so since 1 was the odd one out. Try this.
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)

junior verge
#

Yep that's it

abstract kindle
#

Aren't those interactions?

zealous dagger
#

I need help in that topic

slate swan
abstract kindle
#

I used to know how to use those, I have some old code that uses them. But they were a little finnicky

zealous dagger
#

Ok

#

So here's my code

slate swan
#

What a beutiful code

keen lynx
abstract kindle
#

He best not be typing out that code

slate swan
#

He is

slate swan
zealous dagger
slate swan
#

ctrl+c, ctrl+v

slate swan
zealous dagger
#

You remeber

cloud dawn
#

Ashley is Selects and dropdown expert.

zealous dagger
zealous dagger
slate swan
zealous dagger
#

come in ads

#

I will tell you everything

slate swan
#

...

cloud dawn
zealous dagger
#

What is happining

slate swan
slate swan
cloud dawn
abstract kindle
#

just learned control A

#

I always been using control shift back arrow

slate swan
#

this chat's a mess smh

cloud dawn
zealous dagger
#

Ohhhhhh oh

slate swan
#
@bot.event
async def on_message(message: discord.Message):
    if message.guild is None and not message.author.bot:
        print(message.content)
    await bot.process_commands(message)

How to define the bot ?

  File "main.py", line 24, in <module>
    @bot.event
NameError: name 'bot' is not defined```
maiden fable
zealous dagger
#

Hey hunter

slate swan
slate swan
cloud dawn
maiden fable
#

Nvm, I'm out just gonna get back to thinking about my website design

maiden fable
abstract kindle
#

It's a bunch of discord users trying to code discord bots. Not sure if we're gonna be the most professional

maiden fable
zealous dagger
cloud dawn
maiden fable
#

It doesn't even exist rn

#

Just thinking of the design

slate swan
cloud dawn
slate swan
slate swan
#

But it dont print the messages that sent to the bot in DM

#

Show your full code

#
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = "!")

@bot.event
async def on_message(message: discord.Message):
    if message.guild is None and not message.author.bot:
        print(message.content)
    await bot.process_commands(message)
slate swan
cloud dawn
slate swan
#

After whole code or just after that code?

slate swan
manic wing
cloud dawn
slate swan
#

It should print the output right?

#

But it dont print it

slate swan
zealous dagger
slate swan
slate swan
zealous dagger
#

@cloud dawn

zealous dagger
manic wing
#

the -> None is saying that the function doesnt return anything

cloud dawn
# zealous dagger

You can't call a string it's like trying to call someone who doesn't own a phone.

slate swan
manic wing
zealous dagger
#

@client.group(invoke_without_command=True)
async def help(ctx):
  embed_hm = disnake.Embed(title="Categories",description="Please use the Select Menu below to explore the corresponding category")

  async def slct1_callback(interaction):
      await interaction.send("working")
  async def slct2_callback(interaction):
      await interaction.send("working2")
  
  slct = Select(placeholder="Select the command category you want to see",custom_id="20")
  sct_ct1 = SelectOption(label="Moderation",description="For Admins and Mods")
  sct_ct2 = SelectOption(label="Fun",description="Games and other fun commands")
  #sct_ct1.callback = slct1_callback
  #sct_ct2.callback = slct2_callback

  slct.append_option(sct_ct1)
  slct.append_option(sct_ct2)
 
  view = View()
  view.add_item(slct)

  
  
  await ctx.send("Testing selects for help command!",embed=embed_hm,view=view)

  slct.custom_id()
  
        
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def user(ctx):
    msg = "You're an admin {}".format(ctx.message.author.mention)  
    await ctx.send(msg)
slate swan
#
from discord import Message
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.listen()
async def on_message(message: Message) -> None:
    if message.guild is None and not message.author.bot:
        print(message.content)
        print("working")```
Thats not the full code but part,
No errors, when I send a message to the bot nothing happens.
manic wing
boreal ravine
#

just why

slate swan
#

Doesn't it print anything?

cloud dawn
slate swan
#

nope

boreal ravine
slate swan
#

I just send hi to bot
In DM

cloud dawn
slate swan
# slate swan nope

Are you sure? Perhaps you meant message.channel.send(message.content9 and not print.

cloud dawn
zealous dagger
#

@cloud dawn

slate swan
zealous dagger
#

@slate swan

#

Help

slate swan
#

With?

slate swan
cloud dawn
unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

manic wing
#

!e ```py
def func(a: str, b: int) -> int:

the ide now thinks that a is an str so

it will recognise methods such a .lower()

the ide thinks b is an int so

it will recognise methods such as .to_bytes()

return 5 # this fufills the -> int because the function

is returning an int

num = func('a', 1) # ignore the variables i pass here

the ide now knows that num is an int

unkempt canyonBOT
#

@manic wing :warning: Your eval job has completed with return code 0.

[No output]
manic wing
#

typehinting is very useful

slate swan
# slate swan Done, still not working

What happens if you use this?```py
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents= discord.Intents.all())

@bot.listen()
async def on_message(message):
if message.guild is None and not message.author.bot:
print(message.content)
print("working")
else:
print("not in dms")

#

yeah it will even highlight the methods and recommend those

cloud dawn
slate swan
#

Thats full code

from json import load
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents= discord.Intents.all())

@bot.listen()
async def on_message(message):
    if message.guild is None and not message.author.bot:
        print(message.content)
        print("working")
    else:
        print("not in dms")

with open('config.json') as g:
  d = load(g)
  token = d["token"]

header_data = { 
      "authorization": str(token), 
}  ```
pliant gulch
#

Shame not a lot people use annotations considering python's community size

pliant gulch
#

Stubs are neutral evil

cloud dawn
#

Public static void Main when?

abstract kindle
#

Question. If I want to use this function in another file

            user_in_database = await collection.find_one({"_id": ctx.author.id})
            if bet > user_in_database["money"]:
                await ctx.send(
                    f"You don't have enough to place this bet.\n(Balance: *{user_in_database['money']} coins*)")
                return
            # If their bet is 0, stop the code
            elif bet == 0:
                await ctx.send("You can't bet 0 coins.")
                return
        await bet_checks()

How would I do so?

cloud dawn
#

Assuming you got an init ofc

abstract kindle
#

It's not showing up when I do that..

#

Is it normal to have an init file for a Cogs folder?

cloud dawn
#

You got an init file?

slate swan
cloud dawn
abstract kindle
#

Okay cool

slate swan
#

Is it online? @slate swan

cloud dawn
abstract kindle
#

I can imagine. Where should I store that function then?

slate swan
pliant gulch
#
#a.py

__all__ = ("check",)

async def check() -> bool:
    ...
#__init__.py
from .a import *
#b.py

from .a import check
``` prob
cloud dawn
slate swan
slate swan
slate swan
abstract kindle
#

It's in one of my gambling game's files

manic wing
#

your what? o.O

slate swan
abstract kindle
#

I have a cog called HighLow and it's in that file

slate swan
#

finally

pliant gulch
slate swan
#
interaction.response.send_message('Clicked!')
junior verge
#

I got a kick command in my cog, how do I make it when someone that doesnt have perms type the command it will give a error with that he does not have enough perms

slate swan
cloud dawn
abstract kindle
#

@junior verge error handling

junior verge
#

Yeah can you link?

pliant gulch
unkempt canyonBOT
#
**PEP 420 - Implicit Namespace Packages**
Status

Final

Python-Version

3.3

Created

19-Apr-2012

Type

Standards Track

slate swan
#

hi help me?

slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
abstract kindle
#
    highlow.py
    crash.py
junior verge
abstract kindle
#

Should I put an init file in this folder?

slate swan
#

..

cloud dawn
unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

slate swan
#

hi?

abstract kindle
#

And then in that init file, just import the function from its root file?

manic wing
junior verge
slate swan
#

!d discord.ext.commands.Command.error

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`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") event limited to a single command. However, the [`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") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
cloud dawn
slate swan
placid skiff
slate swan
#

ok.

slate swan
placid skiff
#

commands also have an error method, so you can do an error handler for a single command like doing this:

async def my_command(ctx):
  pass

@my_command.error
async def my_command_error(ctx, error):
  pass
abstract kindle
#

Maybe we mean the same thing

cloud dawn
#

Lemme make you as small example

junior verge
# slate swan Use one of that <@!813824599522541628>
@kick.error
    async def kick_error(error, ctx):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
            await ctx.send(embed=em)
``` like that or do I need to do `self` as well
#

before error

placid skiff
manic wing
#

may be better to have a global error handler for that

abstract kindle
#

Just make a handler that handles all missing permissions errors

junior verge
#

How?

abstract kindle
#

Basically same thing as you have there just change the name

junior verge
#

to?

placid skiff
#

using the on_command_error event

slate swan
junior verge
#
@kick.error
    async def error(self, error, ctx):
        if on_command_error(error, commands.MissingPermissions):
            em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
            await ctx.send(embed=em)
``` What do I put as name there then? don't really get it sorry
slate swan
maiden fable
#

no

slate swan
# junior verge to?
@bot.listen("on_command_error")
async def uwu_command_error(ctx, error):
  if isinstance(error, your_uwu_error_obj):
    ...
abstract kindle
#

She means anything you want

slate swan
abstract kindle
#

Just make it descriptive

slate swan
#

^^

abstract kindle
#

For example, this handler is only handling errors that deal with missing permissions

#

So name it something after what it's handling

slate swan
#

yeah, if you wanna do the same stuff with every other command, use a global error handler

abstract kindle
#

if isinstance(error, commands.MissingPermissions):
the commands.MissingPermissions is the only error that this handles

junior verge
#

uh like that?

@client.listen("on_command_error")
    async def error(self, error, ctx):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
            await ctx.send(embed=em)
slate swan
#

if isinstance

abstract kindle
#

mb

abstract kindle
#

I copied from his code

slate swan
junior verge
#

it says client is not defined though

maiden fable
#

try bot

junior verge
#

I don't use bot

slate swan
maiden fable
#

if that also doesn't work, then ๐Ÿ™ amen

junior verge
#

lol

maiden fable
#

cba to guess your instance name anymore

junior verge
#

Shouldn't it just be client then?

#

inside my cog btw

abstract kindle
#

What did you make it

junior verge
#

Just got it as client still

abstract kindle
#

If it's in a cog wouldn't it be @commands.Cog.listener

cloud dawn
#

@abstract kindle ```py
Root-folder
|
Cogs
|
init.py
fun.py
utils.py
main.py

main.py

from cogs.fun import run_func

run_func()

fun.py

from cogs.utils import add

def run_func() -> None:
print(add(1, 2))

utils.py

def add(n1: int, n2: int) -> int:
return n1 + n2

abstract kindle
#

Then put that

junior verge
#

lemme try okay

#
@commands.Cog.listener("on_command_error")
    async def error(self, error, ctx):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
            await ctx.send(embed=em)
placid skiff
#

why you indent

#

it's a decorator, not a function

abstract kindle
abstract kindle
#

Hmm ok

#

Normally there's an auto complete option when I'm importing, and I'm not getting that..

abstract kindle
#

PyCharm

#
            user_in_database = await collection.find_one({"_id": ctx.author.id})
            if bet > user_in_database["money"]:
                await ctx.send(
                    f"You don't have enough to place this bet.\n(Balance: *{user_in_database['money']} coins*)")
                return
            # If their bet is 0, stop the code
            elif bet == 0:
                await ctx.send("You can't bet 0 coins.")
                return```
This function is inside of one of my commands in my HighLow.py file, which is inside my Cogs folder
#

When I try to import it anywhere, it doesn't show up

cloud dawn
#

That also autocompletes, al tough they are a bit of an ass when it comes to local imports. They want you to make a local package of it instead with a setup etc.

vale wing
#

Are you sure you have __init__.py in your Cogs folder

abstract kindle
#

Yep

#

I'm 100% suspicious of it being asynchronous here

#

because I can import functions that aren't

slate swan
#

channel name is author id

     async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
            a = interaction.author.id
            if a in interaction.guild.channels:
                await interaction.response.send_message('Clicked!')
slate nymph
#

how do you sync multiple guilds in an app command?

vale wing
vale wing
#

That won't ever work

slate swan
#

im making ticket command

slate swan
vale wing
#
if str(a) in [c.name for c in interaction.guild.channels]```
slate swan
#

alright

vale wing
#

You gotta check for name

slate swan
#

yes

vale wing
#

But it is better to do a for loop with a break instead of full list comprehension

slate swan
#

ok.

#

first ill test that out

vale wing
#

Or like

a = str(a)
if any(a == c.name for c in interaction.guild.channels):```
hollow carbon
#

how can i ctx the web photo

slate swan
#

its working fine ๐Ÿ‘

boreal ravine
hollow carbon
#

yes

vale wing
slate swan
#

ctx the web photo wdym?

boreal ravine
#

whats a web photo?

hollow carbon
#

how can i Send picture message (web) i mean the bot send

boreal ravine
slate swan
#
@client.command(name="gstart", aliases=["gs", "gq"])
@commands.has_permissions(kick_members=True)
async def gstart(ctx, time=None, *, prize=None):
    if time == None:
        return await ctx.send(':wt: Wrong **TIME** Input!')
    elif prize == None:
        return await ctx.send(':wt: Wrong **PRIZE** Input!')

    gwend = datetime.now() + time
    gwembed = discord.Embed(title = f":wt: {prize}", description = f':wt: Hosted by: {ctx.author.mention}\n :wt: React with :tada:  to enter!\n :wt: Ends in: <t:{int(time.mktime(gwend.timetuple()))}:R>!', color=0x5C71DE)
    gwembed.timestamp = datetime.utcnow()
    gwembed.set_footer(text=f"1 winner ")

    convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, "w":604800, "sec":1, "mins":60,"seconds":1, 'minutes':60, 'hours':3600, 'days':86400, "weeks":604800}
    gwtime = int(time[:-1]) * convertTimeList[time[-1]]
    
    gwmsg2 = await ctx.send(':wt: **NEW GIVEAWAY!** :wt:', embed=gwembed)

    await gwmsg2.add_reaction(":wt:")
    await asyncio.sleep(gwtime)

    new_msg = await ctx.channel.fetch_message(gwmsg2.id)

    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(client.user))

    winner = random.choice(users)
    server = ctx.guild
    await winner.send(f":tada: **GG!** You won {prize} giveaway in **`{server}`**!")
    await ctx.send(f":tada: Congratulations! {winner.mention} won the Giveaway! \n:tada: **{len(users)} Entrants!** :wt:")

bot runs without errors but the command is unresponsive

abstract kindle
#

Panda here?

boreal ravine
#

No

#

only python is here

hollow carbon
boreal ravine
boreal ravine
hollow carbon
#

what?!!!!

slate swan
hollow carbon
#

But i added

boreal ravine
#

oh

boreal ravine
slate swan
slate swan
#

You cannot add str to a datetime.

slate swan
hollow carbon
#

oh fk i write it down on github code

slate swan
junior verge
slate swan
#
@client.event
async def on_command_error(ctx, error):
  await ctx.send(f'{error}')
boreal ravine
junior verge
#

It just didn''t give any error when someone without permission tried

slate swan
junior verge
#
@commands.Cog.listener("on_command_error")
    async def test(self, error, ctx):
        if isinstance(error, commands.MissingPermissions):
            em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
            await ctx.send(embed=em)
``` so this would work then?
slate swan
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send('**Wrong command usage kindly put the correct arguments**')
slate swan
craggy cloak
#
bot = discord.Bot(
    intents=intents,
    allowed_mentions=discord.AllowedMentions(
        everyone=False, roles=True, users=True, replied_user=True
    ),
    activity=discord.Activity(
        type=discord.ActivityType.competing, name="a Simon says event!"
    )

Code:

slate swan
slate swan
#

Because it's commands.Bot unless you're using our beloved pycord Library ๐Ÿ’€

junior verge
boreal ravine
craggy cloak
#

ok so I need to install pycord ok thx

maiden fable
slate swan
maiden fable
slate swan
#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
slate swan
#

use this.

craggy cloak
# maiden fable `discord.ext.commands.Bot`

New error:

Traceback (most recent call last):
  File "main.py", line 79, in <module>
    @bot.user_command(name="Eliminate")
AttributeError: 'Bot' object has no attribute 'user_command'

maiden fable
#

well, idk about that ngl, which module u using

slate swan
slate swan
slate swan
abstract kindle
#

Are init files in Cog folders a thing?

slate swan
#

you can have __init__.py files anywhere depending on your usage

abstract kindle
#

If so, how do I avoid the error of the init file having no setup function

slate swan
slate swan
#
def setup(bot): pass``` thats all.
abstract kindle
#

I see. I tried that but forgot the bot part

#

Thanks

boreal ravine
#

they made a new class iirc

maiden fable
#

Ah

slate swan
static chasm
#

elho

keen lynx
junior verge
abstract kindle
#
async def get_commands(ctx, cog):
    commands = await get_commands(cog)
    await ctx.send(commands)```
Help I feel dumb
#

This is telling me get_commands is missing a positional argument 'cog'

maiden fable
#

bot.get_cog().walk_commands()

abstract kindle
#

oh

#

Walk_commands?

maiden fable
#

!d discord.ext.commands.Cog.walk_commands

unkempt canyonBOT
abstract kindle
#

it's telling me NoneType doesn't have the attribue walk_commands()

#

I don't believe it.

slate swan
#

Then you didn't get the cog.

slim ibex
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
maiden fable
abstract kindle
#

!d discord.ext.commands.Bot.get_cog

unkempt canyonBOT
#

get_cog(name, /)```
Gets the cog instance requested.

If the cog is not found, `None` is returned instead.

Changed in version 2.0: `name` parameter is now positional-only.
slate swan
#

Yeah, you didn't get in the right name.

abstract kindle
#

What does the cog name have to include

#

I've been trying this f"Cogs.{cog}"

#

just cog doesn't work either

slate swan
#

You probably misspelled the name when you used get_cog.

abstract kindle
#

Nothing is working. Anything I put in comes out as NoneType

slim ibex
#

what even is your code

abstract kindle
#
async def get_commands(ctx, cog):
    print(cog)
    commands = bot.get_cog("HighLow.py").walk_commands()
    await ctx.send(commands)```
cloud dawn
abstract kindle
#

I got it to print ALL the commands of my bot

#

But I can't get it to print them for just a Cog

slate swan
cloud dawn
unkempt canyonBOT
slate swan
#

The type of file shouldn't be written

abstract kindle
#

Yeah

#
commands = bot.get_cog("HighLow").walk_commands()
AttributeError: 'NoneType' object has no attribute 'walk_commands'```
#

This error every single time

slate swan
#

Maybe, cogs.HighLow.

abstract kindle
#

Yeah nothing is working here PensiveWobble

slate swan
#

doesnt bot.commands already show all commands including cogs or are you trying to do like a category?

abstract kindle
#

Trying to have it show me all the commands in a single cog

slate swan
#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
slate swan
abstract kindle
#

Yeah

#

It's in "Cogs"

slate swan
#

You do know that you shouldn't enter the file name, you should enter the name you entered when you used the setup function right?

abstract kindle
#

Yeah that's what I've been trying. Still showing up as NoneType

slate swan
slate swan
slate swan
dull sorrel
#

Is there any way to define multiple on_message function?

abstract kindle
#

Gave me hope, but even when I change the name to the setup name it's still NoneType

slate swan
slate swan
unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
abstract kindle
#

question, how do you get your code to have color when sending through discord

slate swan
slate swan
#

Yes

#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
slate swan
#

check the name arg

#

name is not a kwarg there

#

typo

#

hey i wanted to know how can i mention all the users at once whoever reacted on a message reaction?

#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.

The `after` 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.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
slate swan
#

use the async iterator to get the users, and use .mention property

cloud dawn
#

I'd use a join as well.

slate swan
abstract kindle
#

Getting closer guys

@bot.command()
async def get_comms(ctx, cog):
    cmds = bot.get_cog(cog).get_commands()
    await ctx.send(cmds)
#

This gives me [<discord.ext.commands.core.Command object at 0x1027840d0>]

#

I had to change the name of my function ๐Ÿ˜‚ didn't even realize it was the same as the discord.py get_commands()

brave vessel
#

what do you want to send about the command with get_comms? i assume you'd want to put it all in an embed

abstract kindle
#

Probably, and I'll make that happen later. Unless its critical to getting information out of the object

brave vessel
#

so what's your expected output overall if you have one?

abstract kindle
#

Just a list of the names of the commands in the specific Cog i request

brave vessel
#

ohh I see

abstract kindle
#

Yeah. It's also for testing purposes so I can learn more about how this all works.

#

!d discord.ext.commands.core.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
abstract kindle
#

I think I know what to do

brave vessel
#

so I think you would have to go through each command in the list of commands you get (cmds) and get the name from each one

brave vessel
slate swan
#

how to add a reaction to the command output?

abstract kindle
#

Got it!

async def get_comms(ctx, cog):
    cmds = bot.get_cog(cog).get_commands()
    await ctx.send(bot.get_command(cmds[0].name))```
#

Curious, how do I format my code in python when I send it through discord. Some people have color when they send code..

brave vessel
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.

abstract kindle
#
x = 'test'
print(x)```
#

oh sweet

slate swan
#

I sent an embed first and then want the bot to react to it

abstract kindle
#

Assign the embed to a variable

#

That's step 1

slate swan
#

hEmbed <= my variable

#

For the embed

brave vessel
slate swan
#

kk

brave vessel
abstract kindle
#

yeah, that's ultimately what I meant

#

Forgot it has to be sent before it can have reactions added to it lol

brave vessel
abstract kindle
#

0/2

#

!d discord.Message.add_reaction

#

Score!

slim ibex
drowsy coyote
#

Hey i'm trying to create a Discord bot EZverything was working fine until now, when i try to use pip i get ModuleNotFoundError: No module named 'pip'but pip is installed since i can use "pip help" from the windows terminal Could anyone help me ?

slim ibex
#

pip3

#

and it seems like you re trying to import it?

slate swan
ornate linden
#

What's the difference between Loop.stop() and Loop.cancel()?

slim ibex
ornate linden
#

for tasks in particular

#

are tasks just a port of asyncio loops?

slim ibex
#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
past onyx
#

!e

print("hello World")
slate swan
ornate linden
#

Stop says it

Gracefully stops the task from running.

Unlike cancel(), this allows the task to finish its current iteration before gracefully exiting.
but neither stop() or cancel() stop my task without letting it finish

slate swan
#

!d discord.ext.tasks.Loop.cancel

unkempt canyonBOT
slate swan
#

!d discord.ext.tasks.Loop.stop

unkempt canyonBOT
#

stop()```
Gracefully stops the task from running.

Unlike [`cancel()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel"), this allows the task to finish its current iteration before gracefully exiting.

Note

If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.

If this is undesirable, either remove the error handling before stopping via [`clear_exception_types()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.clear_exception_types "discord.ext.tasks.Loop.clear_exception_types") or use [`cancel()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel") instead.

Changed in version 2.0: Calling this method in [`before_loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.before_loop "discord.ext.tasks.Loop.before_loop") will stop the first iteration from running...
slate swan
#

as sten said, if youre iterating in the task and youre trying to close the loop stop() stops the task after the iteration is done, unlike cancel.

ornate linden
#

Not sure what happened to my code but i was running something along the lines of ```py
[task].stop()
await asyncio.sleep(80)
[othertask].start()

then the other task will start this task

and I was getting errors saying that the first task hadn't completed so the 2nd couldn't start it
#

but now I have it to ```py
await asyncio.sleep(80)
[othertask].start()
[task].cancel()

#

and it's working

#

even though the top was working for me

#

but I had some code in the other task that should have cancelled the task but it didn't```py

Prevent task from throwing an error by starting a running task

while [task].is_running():
pront("ERROR", "Fortune task was already running when sync fired, something has gone terribly wrong.")
[task].cancel()
await asyncio.sleep(1)
[task].start()

maiden fable
#

User Rate Limits

#

Was testing anti spam ๐Ÿ˜‚

junior verge
gaunt ice
#

oof

static beacon
delicate hornet
junior verge
static beacon
#

yes

junior verge
#

let me try

slate swan
#

any alternatives for the break thing

junior verge
#

how to get the full name of a emoji? like <cross:then a number etc

solid rover
#

its an hold discussion but i have the same issue. a "database" is not the solution here.
let's say that the bot is hosted on heroku, it will restart every 2 days; i think.
now, once it restart, it reset every cooldown to 0, the point here is to first save them before the bot shutdown and retrieve them when it start.
so yes, you can host the cooldowns on a db, but how can you get the cooldown of each commands first before the bot shutdown ?

junior verge
#

ye I need that

#

I got it

#

How to add a emoji in a embed's title

vocal magnet
#

this will check every 2 seconds if the task has actually stopped, and only then will continue with code exectution

junior verge
#

Now its this:```py
em = discord.Embed(title='error Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)

ornate linden
#

for whatever reason the only way I can stop my task is by cancelling at the very end now

vocal magnet
#

Does your task never end?

#

What does your task look like?

ornate linden
#

It shouldn't

vocal magnet
#

!paste if it's long

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

vocal magnet
junior verge
#

How do I know

vocal magnet
#

Probably better to set the author icon to the url of th emoji

hushed galleon
#

custom emoji is supported in embed titles so maybe double check the id

vocal magnet
hushed galleon
#

ive ran a few tests on it before

junior verge
vocal magnet
#

It doesn't support markdown though right?

vocal magnet
ornate linden
#
@tasks.loop(seconds = 1)
async def sync():
    time = datetime.now().strftime("%H:%M")
    if time == "12:00":
        # Prevent task from throwing an error by starting a running task
        if fortune.is_running():
            pront("ERROR", "Fortune task was already running when sync fired, something has gone terribly wrong.")
            fortune.cancel()
        fortune.start()
@tasks.loop(seconds = 86400)
async def fortune():
    sync.stop()
    # Declare time now so the exec duration of fortune doesn't matter
    time = datetime.now().strftime("%H:%M")
    
    # Do a bunch of junk here    

    # Flag for fortune taking longer than a minute to exec
    if time != datetime.now().strftime("%H:%M"):
        pront("ERROR", "!!!!!!!!!!!!!!!!!!!!\nFortune task took > 1 minute to execute, DO SOMETHING\n!!!!!!!!!!!!!!!!!!!!")

    # Safeguard against fortune desync
    if time != "12:00":
        pront("ERROR", "Fortune task has become desynced with system time, restarting sync.")
        # Wait so sync task doesn't immediately restart fortune
        await asyncio.sleep(80)
        sync.start()
        # Not sure why I have to use cancel now but I do to actually close fortune()
        fortune.cancel()
junior verge
vocal magnet
#

Bots can only use emojis from servers they are in

ornate linden
junior verge
#

then I know what to do

vocal magnet
#

Invite the bot to that server, add that emoji to the server you're testing with, or use a standard emoji

junior verge
#

I can't it's just a emoji I found because I got nitro

#

I'll just add the emoji to my testing server

vocal magnet
#

๐Ÿ›‘โ›”๐Ÿšซ all of these are standard emojis, so can be used anywhere

junior verge
#

ah ye

thorn ore
#

Any help you guys want?

hybrid mural
#

Hey basically im trying to make a TicTacToe game implementing Buttons(i.e if the top left button was clicked and the turn was from the 1st player, the button gets switched to a Button with an X Emoji etc...) and my problem is Sending the Buttons and formating them. Im trying to send them via ctx.send(components=) but my problem is in how can i format my buttons. I'd need 3 columns but i dont know if components supports that. I cant think of any other way of sending the buttons

delicate hornet
#

why arent the perms request_to_speak stream not in the dev portal?

slate swan
silent ermine
hushed galleon
slate swan
silent ermine
slate swan
silent ermine
hybrid mural
silent ermine
slate swan
hushed galleon
silent ermine
silent ermine
slate swan
hybrid mural
#

Where can i find it?

hushed galleon
slate swan
#

yes, sort of

#

discord.py 2.0 is the name they gave to a few changes on the master branch that were supposed to be published before the discontinuation

#

you should by all means avoid using discord.py, use a trusted, maintained fork instead

slate swan
#

!pypi disnake

unkempt canyonBOT
slate swan
#

the new way of starting a bot with context managers is so weird to me i hate it

hushed galleon
#

ehh datetime timezones and Assets rework too

#

yeah i kinda think its weird too

slate swan
#

could be a lot of things, depends on your implementation of oAuth

winged bone
slate swan
#

It is?

#

How can i create this
Exaple:
list = ["kaka"]
If message contasin in list:
await message.delete()

hybrid mural
slate swan
#

huh, i haven't kept up with the news i suppose

tall dust
#

@cedar smelt please remove the bot invite from your code before posting it

#

it still trips our filters

#

replace it with foobar or whatever

solid summit
#

Discord py is being maintained again, but master branch is not stable enough yet I think

slate swan
hybrid mural
slate swan
river swift
#

If I start to make a bot from scratch, what library do I use?

hybrid mural
hushed galleon
hybrid mural
river swift
#

thx

solid summit
hybrid mural
solid summit
#

With current version I've found myself with some issues

vocal plover
hybrid mural
vocal plover
#

Considering it says 1.7.3 I don't think so

hybrid mural
#

This ones the right one i guess

solid summit
#

yeah

slate swan
#

Hypercorn?

#

What does that mean?

#

!d os.execv

unkempt canyonBOT
#

os.execv(path, args)``````py

os.execve(path, args, env)``````py

os.execvp(file, args)```
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") exceptions.

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using `sys.stdout.flush()` or [`os.fsync()`](https://docs.python.org/3/library/os.html#os.fsync "os.fsync") before calling an [`exec*`](https://docs.python.org/3/library/os.html#os.execl "os.execl") function.
restive drift
#

Any bot developers here?

stray flicker
#

just ask your question, you don't need to ask that

cold sonnet
slate swan
proud rain
#

why is my buttons not being send??

slate swan
slate swan
proud rain
#
@Client.command()
async def button(ctx):
    await ctx.send(
        "",
        components = [
            Button(style=ButtonStyle.red, label = 'test!') 
        ]
    )
    interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
    await interaction.respond(content="test")```
slate swan
#

just why

proud rain
#

??

slate swan
#

why use a third party lib?

#

you can just use main or a fork which are way better

proud rain
#

but how to fix

sick birch
#

Donโ€™t use 3rd party component libraries, bad ones at that

#

They were fine when people were scrambling after d.py archived but why at this stage

slate swan
#

yeah listen to robin prove my point more because he has helper role AG_PepeSad

proud rain
#

so its because i also have nextcord and stuff?

cold sonnet
#

and he's better at his thing

slate swan
cold sonnet
#

yes

slate swan
vocal plover
#

yes

slate swan
proud rain
slate swan
#

yes

proud rain
#

can you send example for a button in nextcord?

cold sonnet
#

jk use what you want

slate swan
#

atleast nexcord wont get archived in 6more monthssmug

cold sonnet
#

except dpy buttons 3rd party lib

vocal plover
cold sonnet
#

I might be missunderstanding

proud rain
#

are there stuff i should turn on in the oath2 invite for the bot to get the buttons to work

vocal plover
#

buttons don't require any scopes other than bot

proud rain
#

okay, but im curious why my buttons don't work. For 2 weeks ago, they worked

loud junco
#

is 1.0 couned as integer hmmm

slate swan
#

!e print(type(1.0))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

<class 'float'>
loud junco
slate swan
loud junco
#

float max 2 dp right?

slate swan
#

pardon?

#

anything that is a decimal is a float

loud junco
#

decimal point

vocal plover
#

no floats in python have much more precision than that

#

~15 digits of precision iirc

loud junco
#

!e print(type(1.000000000000000010))

#

!e print(type(1.000000000000026472162713213123123100010))

vocal plover
#

anything with a decimal point will be a float

loud junco
#

okok

vocal plover
#

it may not retain the same precision its given with however

slate swan
#

if it doesnt have one its an int lol

vocal plover
loud junco
#

what about 0.11111....

slate swan
#

yes

loud junco
#

ok

vocal plover
#

0.1 + 0.2
0.30000000000000004

loud junco
#

so pi is also float?

vocal plover
#

yes

vocal plover
#

though only precise to a certain amount of bits

slate swan
#

whats that called again? when it doesnt do math precisely

vocal plover
#

rounding errors?

slate swan
#

no i think it was called something else

river swift
#

I just installed visual studio code should I also install python?

slate swan
#

i forgotAG_WorrySadge

slate swan
river swift
#

yes ?

#

So now I give you permission to change things on my device right?

river swift
slate swan
slate swan
river swift
slate swan
#

hi

river swift
proud crescent
#

how do i start discord bot prefix

#

indents dont work

#

they break whatever is working

fading nymph
proud crescent
#

?

#

idk

#

i want a ! b4 my command

#

like !exec

stray flicker
#

initialise a bot

#

and use whatever prefix you want

delicate hornet
#

is there a way to get a list of allowed permissions?

river swift
slate swan
river swift
slate swan
unkempt canyonBOT
#

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate โ€œdynamicโ€ command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as itโ€™s likely to cause performance issues and unintended command invocations.

slate swan
river swift
slate swan
#

no thats not for you

#

i replied to the correct message which you arent the author of it.

river swift
proud crescent
slate swan
#

what

river swift
#

.-.?

dry junco
#

How do i fix this ?

  File "c:\Users\dhope\OneDrive\Tyรถpรถytรค\main.py", line 3, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'```
slate swan
#

pip install requests and if you are gonna make request with the lib for your bot use aiohttp

#

!pypi aiohttp

unkempt canyonBOT
bleak karma
#

how do i make the bot send a Ephemeral message when clicking on buttons using discord.ui?

dry junco
hushed galleon
south jetty
#
await ctx.channel.history```
#

how can I get the users that sent a message in the channel

hushed galleon
#

you could iterate through each message and add the author to a set

#

e.g. py recent_users = set() async for message in channel.history(): recent_users.add(message.author)

south jetty
#

confused

hushed galleon
#

on how to use history()?

south jetty
hushed galleon
#

you either use it in an async for loop like in the example, or if you wanted a list you could flatten() it

#

await channel.history().flatten()

tidal hawk
#

authors = [message.author for message in await channel.history(limit=100).flatten()]

#

Does Discord bot need some kind of a permission to see other peoples activities? Because currently the bot is returning nothing (it shows activity on disc tho)

hushed galleon
#

yeah the members intent is needed

tidal hawk
#

it's on

hushed galleon
#

both in dev page and your code?

tidal hawk
#

Oh

#

Intents.presences has to be enabled

tidal hawk
hushed galleon
river swift
#

it gives me this error in the code

tidal hawk
#

That's crazy

slate swan
#

you should use listen and no need for that for loop just check if that string is in the message content string

tidal hawk
#

You are banning them before sending the reason to them xD

#

Also you can't mention after his gone

hushed galleon
# river swift

you should refresh your token, pylance gave out each part of it in that errors list

tidal hawk
#

Send it before you ban him

#

or idk

vocal plover
#

as a side note banning people after just doing a basic keyword check is a really bad idea, what happens if someone says a message like is discord.gg an official website?

south jetty
tidal hawk
#

You can use dict, which removes the dubs

#

set*

south jetty
hushed galleon
#

i would also suggest trying to resolve the invite's guild in case its just an invite to the same guild

vocal plover
slate swan
#

just iterate through bans

#

!d discord.Guild.bans

unkempt canyonBOT
#

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

Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").

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

!d discord.Member.unban and just use this

unkempt canyonBOT
#

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

Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
vocal plover
#

Also in general I'd just not autoban for something so nuanced at all, send an alert to a staff channel or something, but autobanning if you're not 100% confident is generally not a good idea, even in a server with over 400k members we just delete invites, not ban the member without staff approval

slate swan
#

bro i said it

#

bans returns a list of guild bans iterate through it?

dry junco
#

How do i fix this?

  File "c:\Users\dhope\OneDrive\Tyรถpรถytรค\main.py", line 14, in <module>
    eval(compile(base64.b64decode(eval('\x74\x72\x75\x73\x74')),'<string>','exec'))
  File "<string>", line 8, in <module>
ModuleNotFoundError: No module named 'psutil'```
vocal plover
#

you need to install psutil

tidal hawk
#

How do I execute python code in this chat

vocal plover
#

!e

slate swan
#

yes but thats a useless variable

#

Hey everyone. Iโ€™m looking to get an VPS For my bot. What do you guys suggest

#

because you dont need it?

#

the variable is a literal string

#

Whatโ€™s your issue

tidal hawk
unkempt canyonBOT
#

@tidal hawk :white_check_mark: Your eval job has completed with return code 0.

['a', 'b', 'c']
vocal plover
slate swan
#

bro just check the string in the message content which is a string

slate swan
#

whats slowa

vocal plover
slate swan
#

bro i literally just solved your issue

slate swan
solid summit
slate swan
#

scroll up

vocal plover
#

any of the above are fairly easy, the easiest would be Linode or Hetzner because they dont have massive control panels with a ton of features

solid summit
#

Dannys tag on dpy server

slate swan
#

yes.

#

!e

if "lmao" in "lollmaolol":  print(1)
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

1
solid summit
#

haha

slate swan
#

bro its basic oop

#

message wont be defined since its not a message obj of the dpy lib

#

I have 3 VPS in mind and ensure which is better and easy to setup . Digital ocean OR vultr OR galaxy gate

#

Yeah, but you don't accidentally say discord.gg/ inside a sentence.

slate swan
winged bone
#

!e

my_list = [1, 2, 3, 3, 4, 7, 7, 9]
my_set = set(my_list)
print(my_set)
slate swan
unkempt canyonBOT
#

@winged bone :white_check_mark: Your eval job has completed with return code 0.

{1, 2, 3, 4, 7, 9}
vocal plover
#

DO and Vultr are both decent choices, I'd avoid galaxygate since they have worse uptime and pretty crap terms and conditions

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4, 7, 9]
slate swan
#

yes but use listen

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

I have 3 VPS in mind and ensure which is better and easy to setup . Digital ocean OR vultr OR galaxy gate

slate swan
tidal hawk
#

How to check if a class is inside tuple union? For example, check the existence of Spotify in user activities

#

activities returns: Tuple[Union[BaseActivity, Spotify]]

solid summit
#

isinstance?

slate swan
slate swan
#

how should i make a ban command

ivory cave
#

how do u color the message like that ?

slate swan
#

They meant instead of client.event use client.listen.

ivory cave
#

if i may ask

slate swan
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.

ivory cave
#

oh my god i need this bot ๐Ÿ’€

slate swan
#

Wait. With my bot I have txt files where you have to constantly update the txt files because you put your software keys into it. It that gonna miss up the vps?

slate swan
#
@client.event
async def on message```
#

THATS SO COOL OMG

slate swan
#

Alright

solid summit
vocal plover
#

saving lines is less important than making your code readable; you should be optimising for readability and clarity, not shortness

slate swan
vocal plover
#

of course to an extent being short helps, but shortness should be a way of achieving clarity, it should not be the result you are aiming for

tough lance
#

PEP8-

placid skiff
#

essentially, you don't use type hints? your code is unreadable xD

slate swan
vocal plover
#

the idea of esoteric code is not to be clear kek

slate swan
vocal plover
#

no

#

thats absolutely wrong

solid summit
slate swan
tough lance
vocal plover
#

Storage is incredibly cheap and we have a ton of it, saving a few bytes on disk is not worth the mental effort required to parse harder to read code

solid summit
slate swan
#

you guys all missed my point.

vocal plover
#

the mindset that making your code tiny is better will simply limit you from writing good clear code, and understanding what your code does when you read it again a week later

tough lance
#

Well this guy is halfway right tho

solid summit
tough lance
#

It's like writing a diary in your own codewords

#

You won't want to share it with anyone

slate swan
vocal plover
#

Any mental effort required to understand unreadable code is effort you can't be spending on actual application logic, you should be focusing on solving problems with your code and making it better, you should not be focusing on trying to understand what you wrote last week

slate swan
# slate swan you guys all missed my point.

Nah, you want to do ```py
await client.get_guild(6282819182829291).get_channel(93929101032021103).get_member738291933922933).send(embed = discord.Embed(title="ysjaka", description ="ywjwoslalqla"))

#instead of
guild = client.get_guild(288291929931)
channel = guild.get_channel(1992838292919)
member = channel.get_member(28291992939302)
embed = discord.Embed(...)
await member.send(embed = embed)

vocal plover
#

It's a fact that less readable code simply takes more effort to parse, that's effort you don't need to be spending if you just write clean code initially

tough lance
#

Btw why are you guys discussing it here-

slate swan
#

Discord = discussion

slate swan
vocal plover
#

And you use the word optimise a lot; optimising for space complexity doesn't do anything because we have so much space available, and if you need extreme efficiency Python is not the right language anyway, so fine optimisation has no reason to be prioritised over readability

slate swan
slate swan