#discord-bots

1 messages · Page 1150 of 1

visual island
#

I haven't use sql stuff for a while but try these 2 things:

  1. don't commit on every loop (put it after the loop instead)
  2. don't use f-string for the query, use the query parameter
#

but I have no guarantee that it will work

honest shoal
#

nope, you cannot do that message.content there. bumpreminder is the name of command there

swift pumice
#

okay

swift pumice
#

hi guys i have a problem: /home/container/bot.py:718: RuntimeWarning: coroutine 'sleep' was never awaited
asyncio.sleep(10)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

my code

async def bumpremindme(ctx):
    await ctx.send("ok")
    asyncio.sleep(10)
    channel = bot.get_channel(992511703155740712)
    await channel.send(f'{ctx.author.mention}bump again 🤢')```
slate swan
#

It's coroutine

#

asyncio.sleep
await it

#

await asyncio.sleep()

slate swan
#

took me 10 seconds to determine the right spellings for asyncio

swift pumice
#

ok

slate swan
#

my auto correct change that asyncio to Asuncion

swift pumice
#

thanks

slate swan
slate swan
slender stirrup
#

how can i add description to slash command parameters description?

slate swan
#

Bro what the

slender stirrup
#

installed from github not pypi

slate swan
#

you have to specify a guild

#

use ctx.guild

#

Also ur for loop

slender stirrup
vocal snow
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command()
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
robust fulcrum
#

I have no idea how to get these things

slate swan
swift pumice
vocal snow
#

Hello

robust fulcrum
slate swan
#

Well u get an idea

#

nice

robust fulcrum
#

Hmmm

#

Ig i need database?

slate swan
#

Like check recent message of the guild add some checks everytime and all

#

It's easy

robust fulcrum
#

Hmm not related to active channel tho

slate swan
#

channel = bot.get_channel(989514935459540992)
is there a way to use channel names instead of id's

slender stirrup
slate swan
slender stirrup
# vocal snow !d discord.app_commands.describe
@tree.command(guild=discord.Object(id=guild_id), name="roll", description="Rolling Dice")
async def roll(interaction: discord.Interaction, dice:app_commands.Range[int, 1, None]=10):
    await interaction.response.send_message(f"{random.randint(1, dice)}")
paper sluice
robust fulcrum
slender stirrup
#

tree dont have describe method

slate swan
hot basin
#

I just realised that when guild ids get into the mysql get changed into a wrong number

@client.command()
async def insertTables(ctx):
    for guildid in client.guilds:
        print("befor inserting")
        servid = guildid.id
        print(servid)
        #here in console it prints id correctly
        await ctx.send(servid)
        #in discord send id and they are unique and correct
        cur.execute(f"INSERT INTO Servers(serverid,sub,subdate) VALUES({servid},0,CURDATE());") 
        #get changed and saved into db
        conn.commit()
        print("done") ```
anyone knows what is happening i dont event encrypt it and  i dont why is it changing in db
vocal snow
shrewd apex
#

oof global

slender stirrup
robust fulcrum
winter gull
slate swan
vocal snow
unkempt canyonBOT
#

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

Creates a public thread from this message.

You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").

New in version 2.0.
paper sluice
#

iterate over the list

#

which channel do you want?

visual island
slate swan
vocal snow
#

you can just call bot.get_channel in the list comp

paper sluice
# slate swan how??

why do you have a list in the first place, which channel do you want to get?

slate swan
#

That iteration makes no sense, you have a list of channel objects which you are using to get a list of IDs of channel objects, and then convert it to a list of channel objects again????

#

If you want a specific channel use get_channel or ulilts.get straight

slender stirrup
#

can i add subcommand to @tree.command

slate swan
#

There's a class called command group or something in dpy for slash group commands

gaunt mortar
#

Hello, I currently got an issue :
After someone submit a modal, I want to send a DM to an user from his ID, so I need to retrieve it with client.get_user
My issue is, by doing this I'm getting error due to circular import (client trying to load cogs, cogs are using custom buttons that load my modal, which needs client..)

I guess I'm doing something wrong how can I handle this? Thanks for any help 🙂

slender stirrup
#

as i mentioned i use commantTree

#

can work with tree?

slate swan
visual island
slate swan
slender stirrup
#

is there any example

slate swan
#

Check the channel pins, I think there's an example in the gist

gaunt mortar
slate swan
#

Uwu group 💀

paper sluice
#

lol

slender stirrup
#

yes i saw it but i want to implement it to tree

#

bu i don't use any

#

classes or cogs

#

it looks to i have to use cogs

slate swan
warped mirage
#
@client.tree.command(description="Ban a user")
@app_commands.checks.has_permissions(ban_members = True)
async def ban(inter: discord.Interaction, member : discord.Member, *, reason: str):
        try:
            await  member.send(f"You have been banned in {inter.guild} for {reason}, Would you like to appeal? Join this server:")
            await  inter.response.send_message(f"{member.mention} has been banned for {reason}")
        except:
            await inter.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
        finally:
            await member.ban(reason=reason)``` i need help adding a error response , so if user isnt mentioned it says a message
smoky marsh
#

Guys, what is _pycache_

warped mirage
warped mirage
#

np

cloud dawn
smoky marsh
#

Understandable

paper sluice
slate swan
#

in sqlite db table, i have 3 users with some data on them. But i have for loop. Is there a way to make the bot not to spam?

#

this is my structure

#

Eventually append to a string and output as embed description/field depending on the layout you want

cloud dawn
slate swan
#
for i in data:
  embed = discord.Embed(
    description = f"..."
  )
  embed.add_field...
  await ctx.send(embed=embed)```
slate swan
cloud dawn
#

Do recommend keeping in mind the field limits

slate swan
#

Put embed = and ctx.send outside of your loop

cloud dawn
#

And the send under the for

slate swan
#

And embed = before the loop

#

Like the embed = discord.Embed thingy

#

oh

#

ok, so i should add this above the loop

#

correct

#

let me check it

warped mirage
#

what should i do

slate swan
#

@slate swan a problem.... :\

#
embed = discord.Embed()
for i in data:
  embed.add_field(...)
  embed.add_field(...)
await ctx.send(embed=embed)```
#

Right ?

#

I guess

cloud dawn
#

One field is enough

slate swan
#

no

#

but i have staff name and staff hours

cloud dawn
#

Just use the title kwarg as well

slate swan
#

Unless they shrink name and hours of the staff member together

#

let me send screenshot

#

that what im talking about

#

and i try to make list, you know

#

yeah you gotta make some cleaner list

#

something like Name / Hours or similar

#

I try to make something like

Staff Name: Staff Hours:
(mention all users from the table) (send data from table)

#

Yeah as i said

#

gotta make the list differently

tepid sundial
#

Cna i creat / command whit python bot?

slate swan
#

ok with fields and for loop is this possible?

#

no

tepid sundial
#

I persian

slate swan
#

it will never look the same

#

so you can't really do it

tepid sundial
#

If me bad talking

#

Sry

slate swan
#

mobile will be different than desktop

#

you can make the embed description

tepid sundial
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, 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.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
slate swan
#

to something like
Staff Name / Staff Hours
@slate swan / 1337 hours
@slate swan / 7331 hours

slate swan
#

just make sure it respects the chars limit

#

!e
desc = ""
for i in range(0, 10):
desc += f"{i}\n"
print(desc)

unkempt canyonBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
slate swan
#

something like that maybe

#

@tepid sundial #bot-commands for your commands please

tepid sundial
#

!dum

unkempt canyonBOT
#

Dunder methods

Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.

When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.

Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.

class Foo:
    def __init__(self, value):  # constructor
        self.value = value
    def __str__(self):
        return f"This is a Foo object, with a value of {self.value}!"  # string representation
    def __repr__(self):
        return f"Foo({self.value!r})"  # way to recreate this object


bar = Foo(5)

# print also implicitly calls __str__
print(bar)  # Output: This is a Foo object, with a value of 5!

# dev-friendly representation
print(repr(bar))  # Output: Foo(5)

Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!

tepid sundial
#

Um

#

Ok

#

Sry

#

can i creat a / command?

#

whit python?

cloud dawn
#

You can

slender stirrup
#

I'm adding cog from other file stats and roll commands are duplicated

slate swan
#

maybe you created the commands with global scope first and then guild wise, or vice-verse

slender stirrup
#

other file just contains 2 command which are roll and stats

slate swan
#

just purge all the commands once

slender stirrup
#
class BitikBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix="!", intents=discord.Intents.default())
        self.count = None

    async def setup_hook(self) -> None:
        await self.add_cog(fun.Fun(self))
        await self.add_cog(MySlashGroupCog(self))
        self.tree.copy_global_to(guild=discord.Object(id=993917768757940224))
        await self.tree.sync()

    async def on_ready(self):
        live_counter.start()
        print(f"We are logged in as {self.user}")
slate swan
#

As said above, purge them all once

paper sluice
slate swan
#

You probably have a guild command and a global command

slender stirrup
#
class Fun(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

        self.mongo_client = pymongo.MongoClient("")
        self.col = self.mongo_client[""][""]

    @app_commands.command(name="roll", description="Zar yuvarlar.")
    @app_commands.describe(dice="Maximum değer giriniz.")
    async def roll(self, interaction: discord.Interaction, dice:app_commands.Range[int, 1, None]=10):
        await interaction.response.send_message(f"{random.randint(1, dice)}")

    @app_commands.command(name="stats", description="Sunucu istatistiklerini gösterir.")
    async def stats(self, interaction: discord.Interaction):
        print("asdjujklasşdaskdjıokpaslğspkojıduh============================")
        if self.col.count_documents({"_id":interaction.guild_id}) != 0:
            print("eski kayıt")
            await interaction.response.send_message("test")
        else:
            print("ynei kayr")
            await interaction.response.send_message("test")
warped mirage
#

Btw guys I wanna learn python myself and stuff, can someone refer me to any good videos or something, I want to be a professional

slate swan
#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

corey schafer

warped mirage
paper sluice
slate swan
#

It's a YouTube channel

#

Search it up

warped mirage
#

Could I possibly learn quite a lot and make stuff eventually?

slate swan
#
slate swan
#

if you want to learn faster, try codewars or something

warped mirage
#

Ok

#

I don’t care even if it takes like couple of months

#

As long as I can learn alot I’m down

slender stirrup
slate swan
#

Follow your status

cloud dawn
slate swan
warped mirage
#
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(inter: discord.Interaction, member : discord.Member, *, reason: str):
        try:
            await  member.send(f"You have been banned in {inter.guild} for {reason}, Would you like to appeal? Join this server: ")
            await  inter.response.send_message(f"{member.mention} has been banned for {reason}")
        except:
            await inter.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
        finally:
            await member.ban(reason=reason)```would this work for a prefix command
slate swan
#

There's no error handler so yeah

cloud dawn
slate swan
#

Probably not working as you want it to work

cloud dawn
#

Since this won't work

warped mirage
#

I’ll add a error handler for the ban command

slate swan
#

prefix commands don't take an inter, they take context

#

The first paremeter is a discord.Context object, but try hybrid commands as said above.

warped mirage
#

Aha ok thanks for letting me know, discord.py 2.0 has been killing me and I forgot sorry

slate swan
#

ok.

cloud dawn
unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
warped mirage
cloud dawn
#

Is none else it's a required keyword arg

slate swan
#

doesn't change

warped mirage
#

Ok

#

Wait so how should I do a error handler for the ban command

#

also , py @client.command(name="sync") async def _sync(ctx: commands.Context): client.tree.copy_global_to(guild=discord.Object(id=)) await client.tree.sync() how can i make this global for slash commands , im making a public bot

cloud dawn
cloud dawn
unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
cloud dawn
#

This is both a prefix and slash command discord.py made this so you won't have yo do things twice.

warped mirage
#

omg so it will form a prefix and slash command?

kind wind
#

Is it possible for discord.Message.content to select a certain str? ex. discord.Message.content(1)

cloud dawn
#

Yes lol I'm trying to explain that to u for the last 3 min

warped mirage
cloud dawn
warped mirage
#
client = commands.Bot(command_prefix = '!', intents=intents)``` do i have to change this?
kind wind
slate swan
#

split the string and take the argument needed

smoky marsh
smoky marsh
slate swan
#

unfunny

smoky marsh
slate swan
#

good for you, but were here to help with discord bots and not go ot :))

smoky marsh
cloud dawn
#

@slate swan could you explain hybrid to @warped mirage I'm on phone ;-;

slate swan
kind wind
# slate swan split the string and take the argument needed

im making a bot for translation (not a translate bot (fr->en) and i want to have multiple words (ids) but not have a command for all of them
example: tv!translate es 3 Hola
<lang> <id> <new translation>

i am trying right now using if functions

slate swan
#

use commands

#

not the on_message event

#

i kinda stopped bot dev before the timeout endpoint was even a thing

kind wind
slate swan
#

Use paremeters

smoky marsh
#

Is learning async necessary?

cloud dawn
smoky marsh
slate swan
#

Yes.

smoky marsh
slate swan
slate swan
slate swan
slate swan
cloud dawn
smoky marsh
slate swan
smoky marsh
slate swan
#

im taking a networking course thats 70 hours long and is pretty general talk of networking lol

slate swan
#

you use Go for the matter right? you work with cyber security which you would need to know networking i assume

vocal snow
slate swan
#

yuh

slate swan
warped mirage
vocal snow
#

Network

slate swan
slate swan
cloud dawn
#

Okimii making his own network protocol

slate swan
slate swan
# smoky marsh Any recommended resources?

This series of videos introduces AsyncIO to Python programmers who haven't used it yet. The first episode is a high-level view on the async ecosystem. We cover:

  • why you'd want to use asynchronous code at all;
  • how latency drives the user experience;
  • what the difference between concurrency and parallelism is;
  • some of the problems you can...
▶ Play video
slate swan
paper sluice
slate swan
slate swan
slate swan
smoky marsh
slate swan
slate swan
slate swan
slate swan
smoky marsh
slate swan
slate swan
smoky marsh
smoky marsh
vocal snow
slate swan
#

i might watch it to get time pass faster

slate swan
smoky marsh
#

That series is just so huge

slate swan
#

yeah probably because you have more knowledge

shrewd apex
#

70hr long

slate swan
#

its like a web article

shrewd apex
#

link?

slate swan
#

personally i always try to not go on youtube for any coding tutorial or explanations, usually horrible

vale wing
#

Same

#

I read docs and stackoverflow 😳

slate swan
#

yeah same, but more often blog articles or something similar before SO

#

im currently network protocols and architecture

#

they even have questions and modules pretty fun ngl

#

and labs !

#

made by cisco hmm

#

probably some advertisement at the end of the course on how to setup a network with cisco router or similar

#

they even show how to make a network with a packet tracer which is cool

slate swan
#

at least it's interactive

#

but its free so give it a chance yk

slate swan
slate swan
slate swan
paper sluice
#

oki is prepared for codejam

slate swan
paper sluice
#

he will carry his team

slate swan
slate swan
#

Thanks 😄

slate swan
paper sluice
#

but you will carry 😳

slate swan
#

college yuck

slate swan
paper sluice
#

👀 wow

slate swan
#

which i havent finished cuz of my course and i made some calculations with 70 hours i would need to atleast do like 5 hours a day to not be reading the whole course for a month

#

@slate swan am i the only one that has a stroke remembering network protocols😔 😭

#

don't need to know every single one

#

the most useful/used you will learn them with the time

#

who said i didnt🤨 😳

cloud dawn
#

Me

slate swan
#

exercises etc. will help you remember the most important ones

#

yeah to me its easier to learn them when its implemented in a problem

slate swan
warped mirage
#

can someone teach me how to use hybrid commands

#

or, how to make a ban error function for missingRequiredArgument]

scarlet aurora
#
@bot.command()
async def banlist(ctx):
    guild = bot.get_guild(971542589859844136)
    list = [515131107696443393]

    for item in list:
        await guild.fetch_member(item)
        return

    for user in list:
        if user == bot.user:
            continue
    await user.ban()```Can someone help?
#

no error or runtime error

#

just doesn't work

tired hinge
#

channel ids in discord are ints or strings?

scarlet aurora
#

ints

slate swan
#

theyre unique integers referenced/represented as snowflakes

paper sluice
#

!e

def foo():
    return
    print('hi')

foo()
unkempt canyonBOT
#

@paper sluice :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

!d return

unkempt canyonBOT
#

7.6. The return statement


return_stmt ::=  "return" [expression_list]
``` [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else `None` is substituted.

[`return`](https://docs.python.org/3/reference/simple_stmts.html#return) leaves the current function call with the expression list (or `None`) as return value...
scarlet aurora
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'ban'

#

that's the error now

#
@bot.command()
async def banlist(ctx):
    guild = bot.get_guild(971542589859844136)
    list = [515131107696443393]

    for item in list:
        await guild.fetch_member(item)

    for user in list:
        if user == bot.user:
            continue
    await user.ban()```
paper sluice
#

you didnt assign this

        await guild.fetch_member(item)
scarlet aurora
#

can I append it to another list?

tired hinge
#

okay so i need a little help here.
how can i check all messages sent in the last 10 minutes in a channel and delete them if they have a certain word?

paper sluice
slate swan
#

you can just ban by ID

#
await Guild.ban(discord.Object(id=<ID HERE>))
#

also don't name your variable as list, its a builtin

scarlet aurora
#

like this?

tired hinge
sick birch
hushed galleon
#

!d discord.TextChannel.history

unkempt canyonBOT
#

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

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

Examples

Usage...
smoky marsh
#

What is the shortest async tutorial lol

#

How much async io knowledge is required for discord bots

warped mirage
sick birch
sick birch
#

I would go a bit more than the bare minimum

slate swan
coarse dawn
#

How do I make the command so I can access it on discord with any big and small letters?

#

Like the command name is "hello" and I write !heLlo

slate swan
coarse dawn
#

Huh?

#

What's aliases

slate swan
slate swan
coarse dawn
#
@bot.command()
async def addData(ctx, value, amount):
``` - how is this made accessible by any form of the command name with big and small letters
sick birch
#

Pass in case_insensitive=True to your bot's constructor

#

(I hope it's true and not false, I'm having a hard time thinking about it lol)

#

Don't know why they didn't just call it case_sensitive: bool but whatever

slate swan
#

you pass true and it would make it case insensitive if you pass false it will make it case sensitive

winter gull
#
if isinstance(error, commands.Forbidden):
        await ctx.author.send(f"Missing Perms {error}")

is this right way to check and send a missing send message perms for the bot?

sick birch
#

Yes.. but do you really want to send it as a DM to command runner?

#

Because that in itself could raise an error, if they have DMs turned off

#

I'm not sure how discord.py handles errors inside error handlers

winter gull
#

idk where else to send the message

#

should i use nested loop?

#

or just log it in a txt or smth?

sick birch
#
role_ids = [123, 456, 789]
await member.add_roles(member.guild.get_role() for role_id in role_ids)
#

It's either that or

await member.add_roles(*[member.guild.get_role() for role_id in role_ids])
vale wing
slate swan
#

Just pass *roles if you already have the roles object in a list, I believe that works

winter gull
vale wing
#

!d discord.ext.commands.Bot.on_error iirc

unkempt canyonBOT
#

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

The default error handler provided by the client.

By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.

Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
vale wing
#

Not a deco

sick birch
warped mirage
vale wing
warped mirage
#

one , py @client.command(name="sync") @commands.has_permissions(administrator = True) async def _sync(ctx: commands.Context): client.tree.copy_global_to(guild=discord.Object(id=)) await client.tree.sync() first of all im making a public bot , how can i make this a global command? its to sync slash commands

sick birch
#

Is it not already global? Seeing as it's a regular prefix command

warped mirage
#

well

#

client.tree.copy_global_to(guild=discord.Object(id=))

#

it asks for a id

vale wing
#

I use that thing for sending traceback to discord

unkempt canyonBOT
#

utils/bot.py lines 106 to 108

async def on_error(self, event_method: str, *args, **kwargs):
    self.log.error("Unhandled exception occured at %s", event_method)
    await self.log_error()```
sick birch
warped mirage
#

i want it so that it works in every guild , is it possible ? or mah

sick birch
#

That depends on what you pass in to your slash command constructors

#

Yes. If that doesn't work try the 2nd method

vale wing
#

I think it's possible only with local checks

warped mirage
#

so its impossible to make multiguild bot with slash commands?

vale wing
#

!d discord.ext.commands.bot_has_permissions for example

unkempt canyonBOT
#

@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.

This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
warped mirage
#

im asking not saying

vale wing
#

How do you think most of bots with slash commands work like dank memer, dyno etc

#

It's possible ofc

warped mirage
#

well i need help with this then.

#

the sync command

vale wing
#

Just dpy 2.0 became user unfriendly

warped mirage
#

so for dpy 2.0 currently not possible?

vale wing
#

Possible

#

But I don't use it so can't help unfortunately

warped mirage
#

can someone here help me

vale wing
#

I mean I can if I do some research

torn sail
#

You can do list comprehension with a * and use discord.Object

slate swan
#

member.add_roles(*[member.guild.get_role(rid) for rid in role_ids])

warped mirage
slate swan
#

hm, yeah

#

given that the IDs in role_ids are correct and perms stuff kirbyangywalk

warped mirage
#

sarth , u good with dpy 2.0 lol

slate swan
#

🚶‍♂️ i don't even like that + its just a basic python thing

#

updated the message already

#

it should be get_role

vale wing
#

@warped mirage could you show your code once again and what do you want it to do

warped mirage
#

ok

#
@client.command(name="sync")
async def _sync(ctx: commands.Context):
    client.tree.copy_global_to(guild=discord.Object(id=)) 
    await client.tree.sync()``` first of all i want to make this multi guild , syncing ,  i want the slash commands to work in every guild
slate swan
#

no problems

warped mirage
#

well u need to enter a id..

#

of one guild but i dont want that

slate swan
#

you want it to work in all servers?

warped mirage
slate swan
#

just don't use the copy_global_to then

warped mirage
#

do i remove that line?

sick birch
# warped mirage wdym

if you pass in a guild ID when creating a slash command, then it will work only in that guild. If you don't pass it in, then it's a global command and will work in all servers. The only problem is that it can take up to 60 minutes for it to propagate

vale wing
#

Just use disnake

slate swan
#

i'd agree with exenifix 😔

warped mirage
slate swan
sick birch
#

Like I mentioned before the whole point of copy_global_to is to copy your global commands to a single guild. I don't see why you need to do that if you want to make a bot that works in all guilds

warped mirage
#

so is that correct? ^^^

sick birch
#

To sync, yes

vocal plover
slate swan
#

i think so, try it and see

warped mirage
#

ok last thing i need help with

sick birch
#

Though I don't really see the point of having a syncing feature on command

#

Might as well just put it on_ready or something similar

warped mirage
slate swan
#

im hating the discord api more and more :V

sick birch
warped mirage
#

can u show me how

slate swan
#

when you realise slash subcommands are just slash command options

sick birch
#
@client.listen()
async def on_ready():
  await client.tree.sync()
slate swan
#

or the setup_hook would be even better!

sick birch
#

I believe that happens before the websocket is fully connected?

#

Don't know if that matters for a REST operation like sync()

slate swan
#

it doesn't, thats purely a HTTP method

sick birch
#

I figured nothing wrong with syncing multiple times, and people are more used to the on_ready anyway

sick birch
slate swan
#

mhm the github example suggests so

warped mirage
#

ok

sick birch
#

You might as well move it into your existing on_ready

#

And move your change presence into a task while you're at it

warped mirage
#

like this?

slate swan
sick birch
#

Which shouldn't be there in the first place (discord.ext.tasks)

slate swan
#

thanks to Oki :D

sick birch
#

Eyup. Once I'm back from this little break I'm going to finish up anything that needs to be done on that and get it merged onto site, and maybe get a !tag for it on the bot as well

slate swan
#

yeah that would be great since there are many beginners who just change the status in on_ready calls

sick birch
#

As evident here haha...

warped mirage
#

i need some help

slate swan
#

check the link you have been redirected to

warped mirage
#

i did

#

i copied it..

slate swan
warped mirage
#

would this just work?

slate swan
#

yeah dont.

warped mirage
#

well then tell me how or what to do

slate swan
#

should be changing it like evvery 30 minutes and in a task

warped mirage
#

no i need it to be updated ever 15 seconds

slate swan
#

i'd recommend something else.

warped mirage
#

whole point lol ]

slate swan
#

since you are setting server count

#

use on_guild_join/on_guild_remove

#

*guild

warped mirage
#

im so confused . ill need help..

slate swan
warped mirage
#

wdym by banned

slate swan
#

as bluenix has told me, discord doesn't like it when you change your presence each certain amount of time, so discord closes the ws connection or ban you iirc per internet protocol

warped mirage
#

are they gonna ban my discord account and bot? tho

#

or what

slate swan
#

your botpithink

warped mirage
#

bro my friends bot is verified , 560 servers and it updates every 5 seconds

slate swan
#

some bots have bigger ratelimits depending in size and i doubt it lol

warped mirage
#

ok then can u help me fix each thing

slate swan
#

because your friend jumps out of a cliff doesnt mean you should as wellpithink

warped mirage
#

ok then help me please.

slate swan
#

i would probably go for the solution sarth has recommended

warped mirage
#

ye but i need the loop....

#

just help me please im confused enough

slate swan
#

not reallypithink

warped mirage
#

live count

slate swan
#

you can probably check the current amount of guilds and then when the event gets dispatched you add a value to the global variable e.g 1 for 1 more guild

warped mirage
#

i want it in the status

#

many bots have it

slate swan
#

then you can change your bots presence but not in a certain time frame

warped mirage
#

can u help me then please

slate swan
#

maybe getting a random time frame like 20mins to 40mins

warped mirage
#

so it updating every 40 mins?

slate swan
#

no no

#

it can be different time each time but in a certain time frame

warped mirage
#

no, i need a live count

#

not random

slate swan
#

!d random.randrange

unkempt canyonBOT
#

random.randrange(stop)``````py

random.randrange(start, stop[, step])```
Return a randomly selected element from `range(start, stop, step)`. This is equivalent to `choice(range(start, stop, step))`, but doesn’t actually build a range object.

The positional argument pattern matches that of [`range()`](https://docs.python.org/3/library/stdtypes.html#range "range"). Keyword arguments should not be used because the function may use them in unexpected ways.

Changed in version 3.2: [`randrange()`](https://docs.python.org/3/library/random.html#random.randrange "random.randrange") is more sophisticated about producing equally distributed values. Formerly it used a style like `int(random()*n)` which could produce slightly uneven distributions.

Deprecated since version 3.10: The automatic conversion of non-integer types to equivalent integers is deprecated. Currently `randrange(10.0)` is losslessly converted to `randrange(10)`. In the future, this will raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
slate swan
#

its not random lol

warped mirage
#

can u please help me then or no?

slate swan
#

you can ig change your presence on each guild join without anything that would do fine ig

warped mirage
#

can u update this for me.

#
@client.event   
async def on_ready():
    await client.tree.sync()
    while True:
        await asyncio.sleep(15)
        await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!support | Im in {len(client.guilds)} Servers"))
        print("Online")
slate swan
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

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

and just change the presence inside of the function

warped mirage
#

idk how

slate swan
#

its a namespace just name a function with that name so when the event gets fired the function gets internally called, hence why i told you to change your presence inside of it

warped mirage
#

bro i need help

#

just help me please

slate swan
#

i have guided you pithink

slender stirrup
#

can commandTree.on_error works with app_command

warped mirage
#

i said i need it to change lively

slate swan
#

which i already told you how it can be done.

#

many ways actually

warped mirage
#

u didnt in which way i need..

slate swan
#

Robin, Sarth and me have helped you, if you cant figure it out maybe you should check out resources

warped mirage
#

u helped the way u like it

#

i said i need it to update whatever duration

slate swan
#

I helped you the way it should be done.

warped mirage
#

bro i need it to be updated,..

slate swan
#

by guiding you to learn and try hard and not be given everything. I am encouraging what this server stands for.

warped mirage
#

then how come wick and those bots have live counts, but i cant??

warped mirage
#

seperate event?

vale wing
warped mirage
vale wing
#

Also updating status every 15 seconds might get you ratelimited

warped mirage
#

wtf it changed , my bot restarted like 7 times

slate swan
warped mirage
#

never had this before

vale wing
#

!d discord.ext.tasks.loop use this instead of while True + asyncio.sleep

unkempt canyonBOT
#

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

no

sick birch
#

Also increase the duration, 15 seconds like mentioned is way too short

#

Maybe a minute to be courteous

warped mirage
#

my bot restarted 7 times with the current code i have , not good ig

slate swan
sick birch
#

Or use on_guild_join

vale wing
#

And if you are trying to change presence when the bot joins a guild it shouldn't even be connected to any events it should be in a loop as well

warped mirage
#

can u help me with that?

vale wing
warped mirage
#

btw if its 30 mins , does ur bot restart after 30 mins?

slate swan
#

it really shouldnt be a certain time span lol

vale wing
#

The function is called every 30 mins

warped mirage
vale wing
warped mirage
#

nah i can make mine every like 30 mins i guess

slate swan
#

just use on_guild_join

warped mirage
#
@client.event   
async def on_guild_join():
    while True:
        await asyncio.sleep(30)
        await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!help | {len(client.guilds)} Servers"))```
vale wing
#

Imagine bot joining 5 guilds at once - 5 useless API calls and ratelimit

slate swan
vale wing
#

Imo it's better to update the amount once in certain interval, not on every guild join

slate swan
#

yup

#

but not really

warped mirage
#

better?

vale wing
#

If you care about live accuracy then on_guild_join if about amount of requests then tasks.loop

slate swan
#

it shouldnt be a certain interval and guild_join can be called many times but you can probably just have a ratelimit or something

warped mirage
warped mirage
#

i alr dod

#

so how often will it update? i wanna set to per 50 mins

slate swan
#

well then you have it

slate swan
vale wing
#

I mean this

@tasks.loop(minutes=30)
async def update_stats():
    await bot.change_presence(activity=Idk(len(bot.guilds)))```
slate swan
#

as told in the namespace description

warped mirage
slate swan
#

iirc ratelimits for dispatching events is like 120/120s

warped mirage
#

iirc?

slate swan
#

if i remember correctly/if i recall correctly

warped mirage
slate swan
#

you would only get ratelimited if you surpass the limit

#

which its 120/120s or 60/120s im not sure

warped mirage
#

how long do u get ratelimited for? if so

slate swan
#

about an hour which i doubt would happen.

hardy yoke
#

if you hit a rate limit you'll just get an error

warped mirage
#

ok uknow what.

hardy yoke
#

if you abuse rate limits too much your bot gets temp banned

warped mirage
#

@slate swan ill do what u suggest. i just want my bot to be fine

slate swan
#

then with what i recommended it would probably be fine lol

warped mirage
#
@client.event
async def on_guild_join(guild: discord.Guild) -> None:
    await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!help | {len(client.guilds)} Servers"))
        ``` so this ye?
slate swan
#

yep

warped mirage
#

wait a sec

#
@tasks.loop(minutes=60)
async def update_stats():
    await bot.change_presence(activity=Idk(len(bot.guilds)))``` should i add this or na
slate swan
#

no need

vale wing
#

That's pseudocode anyway

warped mirage
#

ok, btw if this will be a big problem can i do a command that checks how many servers the bots in? if thats easier

slate swan
#

yeah you can

warped mirage
#

ok so im sorted ig

vale wing
#

Checking amount of guilds is just len(bot.guilds) and len just does simple division not even an expensive operation

slate swan
#

just send the length of client.guilds

warped mirage
#

ye

#

last thing then

#
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason: str):
        try:
            await  member.send(f"You have been banned in {ctx.guild} for {reason}")
            await  ctx.response.send_message(f"{member.mention} has been banned for {reason}")
        except:
            await ctx.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
        finally:
            await member.ban(reason=reason)``` how can i add a missingRequiredArgument error for this prefix command
slate swan
#

nvm you ment argument and not perms

warped mirage
#

ye

slate swan
#

but a local error handler would be what you want

vale wing
#

Just handle it in error handler

warped mirage
#

so i can do it for any command that needs argument and send one message and it will do it for every command?

slate swan
#

just catch all errors in a local error handler and check the instance of the error with an isinstance

vale wing
#

Why local

slate swan
#

well it depends if he wants to do special tasks with that certain error triggered by that command

warped mirage
#

all i want is

vale wing
#

Yes

warped mirage
#

currently all i want is that any command that requires an argument will send a error reply ephemeral saying , You must specify a username

vale wing
#

Ephemeral can't be sent without an interaction

slate swan
#

well Context doesnt have ephemeral messages but an error handler is what you want

warped mirage
#

wait forget ephemeral

warped mirage
#

i can just do delete_after = 10 ?

slate swan
#

it depends on what you want

warped mirage
#

well i said what i want lol

slate swan
#

you just said can i use a kwarg ofc you can use the kwarg lol

warped mirage
#

well

slate swan
#

nothing is limiting you but i just ask because it depends on what you want really

warped mirage
#

so any command that is missing a argument , it sends a reply that it needs to specify a username , then it gets deleted after 10 seconds

vale wing
#

Global error handler does that

warped mirage
#

well any then since i have mute command and them it will be easier ig, but whatever u suggest

hardy yoke
#

read the gist it shows you have to make an error handler to deal with that

slate swan
hardy yoke
#

it's commented to explain most of it as well

warped mirage
slate swan
#

you can just use the name space to redirect the traceback

warped mirage
#

hmm

vale wing
#

Why are people still chaining elif isinstance(error, SomeErrorClass) repetitive code 🤓

warped mirage
slate swan
#

cant you use match and case?

vale wing
#

Dict with error classes as keys and values as responses and there you go

#

Looks much cleaner

slate swan
unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
slate swan
warped mirage
vale wing
#

I have it like some errors derive from my custom class and they have action method so instead of just sending a message they do the action and send the message

warped mirage
#

if anyone can please help

vale wing
#

I forgor where I used it tho

slate swan
#

you would decorate it with Bot.event and use the namespace as your function name so it can be called internally

slate swan
#

sounds familiar

warped mirage
#

Idk you

slate swan
warped mirage
#

Prolly not

slate swan
#

looks like we had dm history

slate swan
#

that one does

#

it passes the Context and error of the command that had the error

vale wing
#

How many lines does python fetch

warped mirage
#

Help me please

slate swan
unkempt canyonBOT
#

utils/errors.py lines 158 to 165

try:
    missing_perms = ", ".join([str(perm) for perm in error.missing_permissions])
except AttributeError:
    missing_perms = None
try:
    missing_roles = ", ".join([str(role) for role in error.missing_roles])
except AttributeError:
    missing_roles = None```
vale wing
#

These are cringe

slate swan
vale wing
#

missing_permissions are most likely a list of str

#

Why am I even casting

hardy yoke
vale wing
#

Ok that really was a list of str

#

Could've done it with map

warped mirage
hardy yoke
#

Please read the gist

warped mirage
#

how else would i have it in my code

hardy yoke
#

That's not how it's formatted in the gist

warped mirage
slate swan
vale wing
hardy yoke
#
    @client.event
    async def on_command_error(ctx, error: Exception):

        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("enter your string etc")`
        #etc etc

warped mirage
vale wing
#

Copysusta

#

Fun fact: I got banned yesterday while testing link regex

warped mirage
#
 @client.event
    async def on_command_error(ctx, error: Exception):

        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(f'Please specify a username.')``` does this work?
slate swan
#

MasterDroid i would recommend you learn OOP, async programming and basic Python as discord.py is a lib that utilizes OOP and asynchronous code, you have been given many sources but have had trouble due to your skill level, sometimes learning a topic over going to the advanced part of it is the best thing to do in order to learn better.

hardy yoke
#

It should but keep in mind that'll run for every command that hits a missingrequiredargument error

hardy yoke
#

A local error handler might be better in certain cases

slate swan
#

if dpys docs cant help you im not sure what can😅

warped mirage
slate swan
vale wing
#

Would the "Guide how to host a python discord bot with docker and github actions" be a useful tutorial

sick birch
#

Definetely useful for the people looking to go one step further, though

vale wing
#

Ok

fallow mauve
#

im making a bot with my friend and i added a rate command where it will pick a random number form 1 to 6 and rate the subject arg that number, but im getting an error, heres code:

from discord.ext import commands
import os
import asyncio
import random
from typing import Optional
import time
from discord.ext.commands import cooldown, BucketType

class RateCommand(commands.Cog):

  def __init__(self, bot: commands.Bot):
      self.bot = bot
      self.last_msg = None


  @commands.command(name="rate")
  async def rate(self, ctx:commands.Context, *, subject):
    if not ctx.guild is None:
      #await asyncio.sleep(random.randint(0,2))
      rateValue = random.randint(1, 6)
      embed=discord.Embed(title=" ", description="** **\n** **", color=0xfffff0)
    
      if rateValue == 1:
        bar = "🟥⬛⬛⬛⬛⬛"
        emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935005847683/unknown.png"
      if rateValue == 2:
        bar = "🟥🟥⬛⬛⬛⬛"
        emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935005847683/unknown.png"
      if rateValue == 3:
        bar = "🟥🟥🟧⬛⬛⬛"
        emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935341379625/unknown.png"
      if rateValue == 4:
        bar = "🟥🟥🟧🟧⬛⬛"
        emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935341379625/unknown.png"
      if rateValue == 5:
        bar = "🟥🟥🟧🟧🟨⬛"
        emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png"
      if rateValue == 6:
        bar = "🟥🟥🟧🟧🟨🟨"
        emoji = hhttps://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png

      embed.add_field(name=bar, value="** **", inline=False)
      embed.set_author(name=f"I rate {subject} {rateValue2.", icon_url=emoji)
      await ctx.reply(embed=embed)




def setup(bot: commands.Bot):
  bot.add_cog(RateCommand(bot))
#

and error:

Traceback (most recent call last):
  File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 839, in exec_module
  File "<frozen importlib._bootstrap_external>", line 976, in get_code
  File "<frozen importlib._bootstrap_external>", line 906, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/runner/Duck-Bot/commands/rate.py", line 41
    emoji = hhttps://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png
                  ^
SyntaxError: invalid syntax

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

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    bot.load_extension("commands.rate")
  File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.rate' raised an error: SyntaxError: invalid syntax (rate.py, line 41)
#

its only line 41 tho

vale wing
fallow mauve
#

ok but i dont get why

#

why is it a bad idea

#

@vale wing

vale wing
#

Just the principle

#

You could do bar like this as well ig

full_bar = "🟥🟥🟧🟧🟨🟨"
print(full_bar[:value] + "⬛" * (6 - value))```
#

!e py value = 3 full_bar = "🟥🟥🟧🟧🟨🟨" print(full_bar[:value] + "⬛" * (6 - value)) 

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

🟥🟥🟧⬛⬛⬛
sick birch
#

You should just be able to look at it and tell

#

Notice how you're repeating the same thing over and over again? Usually that's a bad sign

vale wing
slate swan
#

down bad bro

slender stirrup
slate swan
#

its Member.avatar.url now since avatar returns an Asset obj

#

!d discord.Asset.url

unkempt canyonBOT
slate swan
#

help please ive been trynna fix this for the last 50 mins

flint isle
#

uhh how can I make it to where the reaction is on the sent message?

    @commands.command(name='poll', description='Creates a poll')
    async def poll(self, ctx, *, question):
        """Creates a poll."""
        await ctx.send(f'{question}')
        await ctx.send('React with the appropriate emoji.')
        await ctx.message.add_reaction('👍')
        await ctx.message.add_reaction('👎')
        await ctx.message.add_reaction('❔')
#

i mean the message that the bot sends showing the question

slate swan
#

which channel has tutorials

white aurora
slate swan
#

same error

paper sluice
slate swan
#

Is there a way to add space between 2 words in embed description ?

#

like Word1 Word2

#

and i want Word1 Word2

#

Hello _ _ _ _ _ _ world

#

Hello _ _ _ _ _ _ world

#

yeah

#

That should work I guess

#

i just want to add some space between 2 words

slate swan
#

Yeah then use _ _ per space

#

underscore space underscore

#

ok but are you sure this will work in description of embed?

#

It should

#

Formatting is the same as normal messages

#

i think \u200b should work too but im not sure

#

the underscore didnt work

slate swan
#

love discord

#

What account

#

If you mean yours, it's a selfbot

#

Against Discord ToS

hushed galleon
slate swan
#

!rule 5

dense herald
#

Okay ty

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

can get your account terminated quite easily

slate swan
#

nana

#

Oh ok

#

other person that deleted the message

#

i got a heart attack for a sec

hazy prawn
#

question, how do you get a bot to say stuff at specific intervals like every minute
AND how do you get a bot to say specific stuff based off a chat command with no trigger (like having to say stuff to toggle)

slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

on_message probably

slate swan
#

Is there a way the bot to send only 10 values in embed so i can make embed pages

#

For example, i have selected a table list from sqlite file, which 20 values and i want on the first page to be only 10 and on the second page, the rest of the values (20)

sick birch
#

Some level of JS is going to be required

#

It's not too terribly difficult, I've done it easily. Only with a framework though (for my dashboard)

#

Sure.. are you having any specific issues?

#

Uh yeah I suppose you could ping me

smoky marsh
paper sluice
sick birch
sick birch
paper sluice
sick birch
#

With a little bit of effort from the developer, the user facing side can be really easy. I'm talking 2 clicks to log in with your discord

paper sluice
#

oh nice, thanks

sick birch
#

Yep. I encourage you to implement it yourself, even something that prints out the user's guilds to the JS console and have them go through Oauth2 just to get a feel for how it works

smoky marsh
sick birch
#

I believe there was a realpython on asyncio, reading through that and making sure you understand all of it is a good step in the right direction

#

No, it's all done with your actual discord account

smoky marsh
sick birch
#

If you successfully go with the oauth2 flow, you should have the user's token that you can use for REST operations

#

Yeah I'm here everyday, just send a ping my way and if I'm there I'll see what I can do

smoky marsh
smoky marsh
sick birch
#

I took it down after a while. Wasn't used much and I was primarily doing it for the learning experience, so sadly it isn't up anymore

#

This is a bad idea, you're going to get rate-limited

#

Is your command only supposed to ping a person once in the same channel that they ran the command in?

#

You're on the right track for that, bot.get_channel() only takes one ID at a time however

smoky marsh
#
Traceback (most recent call last):                                                                             
  File "C:\Users\HP\Desktop\Discord Bots\discord_bot1.py", line 4, in <module>                                 
    intents.message_content = True                                                                             
AttributeError: 'Intents' object has no attribute 'message_content'  ```
#
import discord

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

client = discord.Client(intents=intents)

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

@client.event
async def on_message(message):
    if message.author == client.user and message.content.startswith('$hello bot'):
        await message.channel.send(f'Hello {client.user}')
        
client.run('no')```
sick birch
smoky marsh
#

Is the discord docs out of date or something

sick birch
#

The discord docs are on the latest version, which you're not

smoky marsh
cold sonnet
smoky marsh
#

I'm on 1.7.3

sick birch
smoky marsh
#

I ran the command py -3 -m pip install -U discord.py and it says requirement satisfied

mystic star
smoky marsh
#

Okay

#

I ran py -3 -m pip install -U discord.py and it installed 1.7.3 again..

cold sonnet
#

yeah it isn't on pypi

smoky marsh
#

@cold sonnet What?

cold sonnet
#

pip install -U git+https://github.com/Rapptz/discord.py

#

you have to install it from github

sick birch
#

Installing it from pypi will always give you 1.7.3, yeah. Which is why I linked you to the install instructions on github

smoky marsh
#

Ohh okay

slate swan
#

gta6 is coming out first than dpy 2.0 on pypi and thats for sure

cold sonnet
#

lmao

smoky marsh
#
C:\Users\HP>pip install -U git+https://github.com/Rapptz/discord.py
Collecting git+https://github.com/Rapptz/discord.py
  Cloning https://github.com/Rapptz/discord.py to c:\users\hp\appdata\local\temp\pip-req-build-ool05mlr
  Running command git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr'
  fatal: unable to access 'https://github.com/Rapptz/discord.py/': Could not resolve host: github.com
  error: subprocess-exited-with-error

  × git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr' did not run successfully.
  │ exit code: 128
  ╰─> See above for output.

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr' did not run successfully.
│ exit code: 128
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.```
slate swan
#

👁️ 👁️

mystic star
#

lol

hardy yoke
#

what are you trying to do with this because it doesn't make sense from what I'm seeing

smoky marsh
#

Ok I installed it

spark raptor
#

uhh

#

apparently not closed?

sick birch
#

All of that needs to be in a string

smoky marsh
#

What does await do?

sick birch
#

Python doesn't natively understand SQL, so it needs to be inside of a string

#
cursor.execute("SELECT ... FROM ... WHERE ...")
mystic star
smoky marsh
#
import discord

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

client = discord.Client(intents=intents)

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

@client.event
async def on_message(message):
    if message.author == client.user and message.content.startswith('$hello bot'):
        await message.channel.send(f'Hello {client.user}')
        
client.run('my_token')```
Did I use await in the right place
sick birch
#

I believe it also adds it to the event loop

smoky marsh
spark raptor
smoky marsh
sick birch
#

async is used to define an asynchronous function, or a coroutine, while await is used to actually run and wait for the result of said coroutine

sick birch
spark raptor
#

uhhhh where does the comma go?

sick birch
#

It's still not in quotations

#

Python is really confused because you're basically writing another language inside of it

spark raptor
#

im confused as well

sick birch
#

There we go, run it again

spark raptor
#

it's still the same

slate swan
#

only the sql query, the parameters iterable doesnt have to be within the same string

sick birch
#

Also I don't believe SQL lets you use spaces for table names?

paper sluice
spark raptor
#

hmmm

sick birch
#

And yeah good catch, didn't see the (user.id) part at the end

slate swan
#

I always get ignored

paper sluice
#

you didnt type anything pithink

paper sluice
#

oh lol

sick birch
#

To be fair you did kind of phrase that weirdly

slate swan
#

what's weird in that

slate swan
sick birch
#

Probably just nitpicky but it implies that the parameters iterable can be in the same string, but doesn't have to

spark raptor
#

like this?

sick birch
#

I assume they took it as a suggestion and ignored it?

sick birch
paper sluice
sick birch
#
cursor.execute("SELECT ... FROM ... WHERE ...", (...))
slate swan
sick birch
#

I ask myself that sometimes too

#

Don't worry haha, easy issue to fix here anyway

spark raptor
#

whattttttt

slate swan
# slate swan not exactly.

await calls the function and passes the function to the event loop giving control to the event loop so the event loop can manage all the current coroutines to have concurrency

spark raptor
#

oh wait

paper sluice
# spark raptor like this?

and (user.id) is an int not a tuple
it is a little confusing but (something) doesn't make a tuple but (something,) does
so add a comma inside those parens

spark raptor
#

you mean like

slate swan
spark raptor
slate swan
#

or just provide a list or set if it works

paper sluice
tall knot
slate swan
#

best?

spark raptor
#

ok this good?

sick birch
# spark raptor whattttttt

You can't use double quotes inside of double quotes without confusing python into thinking that the quote is done, you can either escape it (\") or use single quotes:

print("Did you know that you can have 'single quotes' inside double quotes? But not \"double quotes\".")
sick birch
slate swan
#

sip dpy has poor app commands design imo

#

its source🗿 pithink

smoky marsh
slate swan
#

I'm talking about both source and user experience

tall knot
#

danny is still trying his best to update the library even after archiving it for 6+ months, def doing way better than what any of us would have tbh ¯_(ツ)_/¯

slate swan
#

I agree, yet expect more from someone like him who has been working on a widely used library for years.

#

And keeping the point in mind that discord.py focuses on simple abstractions, the app commands part kinda suck

slate swan
#

good thing about them is that it provides full control to the library user instead of doing the sync api calls itself, but it's not too hard to implement it in an easy way/optionally

#

my wifi had a stroke

sick birch
slate swan
#

disnake did that, and I like their implementation , tho I use neither

spark raptor
slate swan
hardy yoke
slate swan
#

Yeah that's what I'm taking about

#

!d disnake.ext.commands.Bot

unkempt canyonBOT
#

class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

This class also subclasses [`GroupMixin`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.GroupMixin "disnake.ext.commands.GroupMixin") to provide the functionality to manage commands.
slate swan
#

ow it's in options

paper sluice
slate swan
#

they have a kwarg which stops the lib from making the api calls itself

vocal plover
slate swan
#

` for app commands registration

spark raptor
smoky marsh
#
import discord

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

client = discord.Client(intents=intents)

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

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

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('your token here')```
slate swan
#

yes

paper sluice
smoky marsh
slate swan
#

Event loop closed gives no idea

paper sluice
spark raptor
sick birch
#

Maybe you forgot to actually substitute your token into

client.run('your token here')
```?
smoky marsh
#

I actually did

smoky marsh
paper sluice
#

yup

paper sluice
spark raptor
sick birch
paper sluice
sick birch
#

If I'm to guess it's an intent issue

#

Your bot is requesting intents that you may not have enabled in the dashboard

#

But let's see the full error anyway just to be sure

smoky marsh
spark raptor
smoky marsh
#

Can I upload it as a file?

#

It's too big

paper sluice
unkempt canyonBOT
#

Hey @smoky marsh!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

smoky marsh
#

Ok yes

paper sluice
#

!paste use this @smoky marsh

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.

#

Hey @smoky marsh!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

smoky marsh
smoky marsh
sick birch
#

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

spark raptor
smoky marsh
#

Also, is the discord docs really up to date?

#

Cuz this is the code I'm running in the 2.0.0 version

#

And it's exactly from the docs

paper sluice
#

it is

sick birch
#

Yeah, but the docs will often leave out little things like that

#

But luckily the errors are usually descriptive enough of that to tell you what's wrong

smoky marsh
#

So what do I do

sick birch
#

What does the error tell you to do?

smoky marsh
#

aise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.