#discord-bots

1 messages Β· Page 583 of 1

cloud dawn
#

unbound local error?

slate swan
#

same error as last time

slate swan
cloud dawn
#

?

slate swan
#

no error , it just doesn't trigger

#

the last if statement

cloud dawn
#

That is no error the statement just isn't true

slate swan
#

neither in print statement nor output

cloud dawn
#

debug the if

slate swan
cloud dawn
#

No

slate swan
#

or adding print statement?

cloud dawn
#

print

slate swan
#

already did?

cloud dawn
#
async def on_raw_reaction_add(payload):
    print(f'Is it a bot? {payload.member.bot}')
    k = True if payload.message_id in dict_of_colour_codes.values() else False
    print(f'is message id in dict of colour codes? {k}')
    if not payload.member.bot and payload.message_id in dict_of_colour_codes.values():
        await curchannel.send('hey hey it works')
        new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')

        if payload.channel_id == new_channel.id:
            await curchannel.send('well done')
            print("part 2 was triggered")
#

Run this.

#

What does it print?

waxen granite
#

how do i get the roles in a channel?

cloud dawn
waxen granite
#

no

#

the roles we set for perms in a channel

#

channel permissions for role

cloud dawn
#

pff

waxen granite
#

?

cloud dawn
slate swan
cloud dawn
# slate swan

did curchannel send this message? await curchannel.send('hey hey it works')

slate swan
#

what?

#

are you asking me?

#

or should i run this command?

cloud dawn
#

What is curchannel?

slate swan
#

message.channel

cloud dawn
#

Where is that defined?

slate swan
#

dont use globals in discord bots

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
cloud dawn
#

Or just use OOP

slate swan
#

enough OOP with java

#

why cant you just curchannel = message.channel?

#

great idea

#

is there some need of the variable in other functions

#

idk

#

An error keeps appearing even though I’m handeling it πŸ€’

slate swan
devout iris
#

How can i make a message loop? i.e. ;
me: i!alw
bot: 123
bot: 123
bot: 123
bot: 123
bot: 123
....
Send a message in 5 sec

slate swan
#

i mean , 'what error'

slate swan
#

I’ll send the error

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 424, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
waxen granite
slate swan
#

or just a basic asyncio function task

#

why does the last if not work?

waxen granite
cloud dawn
waxen granite
#

hmm

boreal ravine
slate swan
cloud dawn
waxen granite
boreal ravine
#

hm

#

@slate swan what library are you using

cloud dawn
unkempt canyonBOT
#

class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.

The following implement this ABC...
boreal ravine
#

I dont remember there being a custom id kwarg for views

waxen granite
slate swan
#

There is

boreal ravine
#

πŸ€”

#

link me it

#

hm

slate swan
#

Look at examples/views/persistent

#

It’s on there

boreal ravine
#

m

slate swan
#

and if i try to put that print statement out of that IF block i get referenced before assignment

cloud dawn
slate swan
#

I DID?

#

what other variables?

cloud dawn
#

it wont print ofc

slate swan
#

YES exactly!

#

where do i put it?

#

outside it gives error

cloud dawn
#

Then why did you put it there?

slate swan
#

referenced before assignment

slate swan
cloud dawn
#

πŸ€¦β€β™‚οΈ

slate swan
#

i get error when i put it outside

#

where should i put it?

slate swan
#

how can i fix it

brave flint
#

any docs for music querys?

slate swan
brave flint
#

nope query system

slate swan
#

Like getting music from YouTube

#

Or searching for songs

brave flint
#

nope id like to ...

#

when i playing song , i can add a song to query

waxen granite
#

Role Removed: {<Role id=841588561916854323 name='Moderator , no powers'>}
how can i get the role name from this?

#

removedrole = set(before.changed_roles).difference(set(after.changed_roles))

slate swan
#

So a song list?

brave flint
#

like queue

slate swan
#

Ok

#

Maybe adding the song to a list

brave flint
#

yes and play iy after the first song played automaticly

slate swan
#

Yes

#

You can use time.sleep and file
Eight I guess

brave flint
#

docs?

slate swan
#

length*

brave flint
#

lul

slate swan
#

look at this

dusk dust
#
@bot.command(name='copy')
async def copyforme(ctx, *, message):
    messages = ctx.message

    if message == 'see':
        await ctx.send(messages)

    if message == None:
        await ctx.send('You need to type something!')

    await ctx.send('I will save this message to you. When you want to see your armazened messages, type: ``/copy see``.')

I want it to take the "message" argument and save it to the system. After that, when I type /copy see the bot sends the stored message but, idk how do i can do this. Anyone can help me?

waxen granite
#

wdym

boreal ravine
unkempt canyonBOT
brave flint
boreal ravine
#

Nope

brave flint
#

uh diff people

boreal ravine
#

using disnake atm

waxen granite
# boreal ravine use the objects' attr's

removedrole = set(before.changed_roles).difference(set(after.changed_roles)) embed = discord.Embed(description = f"**Channel Updated:** {after.mention}\n\nRole Removed: {removedrole}", color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())
its a set so its gives error - set has no attr name

boreal ravine
#

hm

#

why is it a set?

waxen granite
#

idk i was trying to get the role

spiral frigate
#
    owner = guild.get_member(637685929611493422)
AttributeError: 'NoneType' object has no attribute 'get_member'

code:

guild = bot.get_guild(894452684072046652)
owner = guild.get_member(637685929611493422)

what's the problem here

spiral frigate
#
    owner = guild.get_member(637685929611493422)
AttributeError: 'NoneType' object has no attribute 'get_member'
slate swan
#

Oh

#

You need to post full traceback I think

unkempt canyonBOT
#

@cloud dawn :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'get_member'
slate swan
#

I want a bot that when I send a message, it will add 3 reacts and when click on one it will dm me with the reaction I clicked

cloud dawn
slate swan
cloud dawn
#

!pypi disnake

unkempt canyonBOT
spiral frigate
boreal ravine
spiral frigate
#

lol

guild = bot.get_guild(894452684072046652)
owner = guild.get_member(637685929611493422)
boreal ravine
#

might be because 894452684072046652 isnt the guild id or something

cloud dawn
#

Or it is just not in the cache

boreal ravine
#

maybe

#

try fetching it

spiral frigate
boreal ravine
#

!d discord.ext.commands.Bot.fetch_guild try this

unkempt canyonBOT
#

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

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_guild "discord.ext.commands.Bot.get_guild") instead.
cloud dawn
#

I recommend making your own function for this.

#

Or take the easy unpractical way of kayle

boreal ravine
#

or you can do guild = bot.get_guild(id) or await bot.fetch_guild(id)

#

both works

cloud dawn
spiral frigate
#

this code is not in the function

boreal ravine
#

its an a function isnt it

cloud dawn
boreal ravine
#

why make a function for something simple

slate swan
#

@cloud dawn help😦 , where do i print that print cmd?

spiral frigate
#

I want to make these variables global

cloud dawn
slate swan
#

it doesnt work in IF, gives error outside if

slate swan
spiral frigate
slate swan
#

what about this?

#

better?

cloud dawn
#

OOP or

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

cloud dawn
#

finally

slate swan
#

thanks!

#

i am sorry i am new to this πŸ˜ƒ

cloud dawn
#

Also print the payload channel

slate swan
#

alright

slate swan
cloud dawn
#

Then look at the print and ask yourself why it isn't the same

slate swan
#

only payload channel id

cloud dawn
slate swan
#

ah ok

spiral frigate
#

I still need them to be available in cog

#

or does doing so not work

self.guild = self.bot.get_guild(894452684072046652)
self.owner = self.guild.get_member(637685929611493422)
slate swan
#

my error handling isnt working

cloud dawn
slate swan
#
    @commands.command()
    async def wallet(self, ctx):
        print("Test")
        db = sqlite3.connect("database.db")
        cursor = db.cursor()
        print("Test")
        cursor.execute("CREATE TABLE IF NOT EXISTS money(wallet_money INT, bank_money INT, member_id INT, guild_id INT)")
        print("Test")
        cursor.execute("SELECT * FROM money WHERE member_id = ? AND guild_id = ?", (ctx.author.id, ctx.author.guild.id))
        wynik = cursor.fetchall()
        if not wynik:
            print("Test")
            sql = "INSERT INTO money(wallet_money,bank_money,member_id,guild_id) VALUES(?,?,?,?)"
            val = (100, 150, ctx.author.id, ctx.author.guild.id)
            cursor.execute(sql, val)
            print("Test")
        print("Test")
        embed = discord.Embed(
            description=f"> :CORRECT: **β€’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
            color=0xff8800,
        )
        print("Test")
        embed.set_footer(
            icon_url=ctx.author.avatar,
            text=ctx.author,
        )
        print("Test")
        await ctx.reply(embed=embed, mention_author=False)
        db.commit()
        cursor.close()
        db.close()

Bot stop at
        print("Test")
        embed = discord.Embed(
            description=f"> :CORRECT: **β€’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
            color=0xff8800,
        )
Logs:
Test
Test
Test
Test
Test
Test
Test
Test
#

finally

spiral frigate
#

There was no such thing where I taught

#

because it's a discord\

slate swan
boreal ravine
slate swan
slate swan
cloud dawn
slate swan
#

its not

slate swan
#

first and last

#

are same

cloud dawn
#

They are not

slate swan
#

they are?

#

new channel is and
2nd payload

#

they both are same?

cloud dawn
#

Why does it print 3 times??

slate swan
#

look the first is new channel id

#

it is when new channel is created

#

okay?

cloud dawn
slate swan
#

and second is when i react to original embed

#

i guess?

#

and third is when i react to new message in new channel

#

i am not sure about the second tho

#

😦 help

keen talon
harsh cradle
#
    @commands.command()
    async def leaderboard(self, ctx):           #toplarΔ± gΓΆsterir
        if (ctx.channel.id == bot_channel):
            rankings = levelling.find().sort("xp",-1)
            i = 1
            embed = discord.Embed(title="Ranking:")
            for x in rankings:
                try:
                    temp = ctx.guild.get_member(x["id"])
                    tempxp = x["xp"]
                    embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline=False)
                    i += 1
                except:
                    pass
                if i == 11:
                        break
            await ctx.channel.send(embed=embed)
``` i have a leveling system with mongo db and i have this leaderboard command and its must show people who have the must exp and it only show Ranking: embed
slate swan
#
Bot stop at
        print("Test")
        embed = discord.Embed(
            description=f"> :CORRECT: **β€’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
            color=0xff8800,
        )
orchid mortar
#

@slate swan

wicked atlas
#

Only catch exceptions that you want to ignore

#

Or handle

slate swan
hollow agate
#
a = await ctx.reply(f'Added the role {role} to {member}!')``` How could I make it mention the role (right now it says the ID) and mention it without pinging the people that have it?
wicked atlas
#

!d discord.AllowedMentions

unkempt canyonBOT
#

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.

This class can be set during [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
ornate lichen
#
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/aarav/GitHub/awaffle_bot/main.py", line 88, in meme
    subreddit=reddit.subreddit("memes")
KeyError: 'data'

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

Traceback (most recent call last):
  File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'data'```
#
async def meme(ctx):
  subreddit=reddit.subreddit("memes")
  all_subs=[]

  top=subreddit.top(Limit=50)

  for submission in top:
    all_subs.append(submission)

  random_sub=random.choice(all_subs)

  name=random_sub.title
  url=random_sub.title

  em=discord.Embed(title=name)

  em.set_image(url=url)
  await ctx.send(embed=em)
#

how do i correct it?

spiral frigate
#

I have a variable welcome
in it the text: Hello {member}, you are on the {guild} server.
Before the output there are variables member and guild and so when they are output they are written as plain text how to solve this

slate swan
#
@bot.command()
async def lock(ctx):
    ctx.guild.channels.set_permissions(ctx.guild.default_role, send_messages=False)

How to change the permission of all text channels ?
error:
Command raised an exception: AttributeError: 'list' object has no attribute 'set_permissions'

steady flume
#

what i need put instead of += ? 281 line

dapper cobalt
dapper cobalt
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.

steady flume
#
    async def callback(self, interaction: discord.Interaction):
        assert self.view is not None
        view: Menu = self.view
        if self.values[0] == "Moderation":
            self.view.variable += "Moderation"
            self.menus[0].default = False
            self.menus[1].default = True
            await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=view)
        elif self.values[0] == "Currency":
            self.view.variable += "Currency"
            self.menus[0].default = True
            self.menus[1].default = False
            await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=view)

unsupported operand type(s) for +=: 'NoneType' and 'str'

#

what i need put instead of +=?

hollow agate
#
await member.add_roles(role)``` How can I make it to where it'll add the role `role`, but it's not adding it because it's an ID. So, I need to convert that ID to something somehow.
slate swan
#

!d discord.Guild.get_role

unkempt canyonBOT
pliant gulch
#

It would be easier to just do create a discord.Object with the id and pass that

tawdry perch
#

isn't this correct way to get a role from server? ```py
role = discord.utils.get(ctx.guild.roles, id=self.default)

#

self.default gives a role ID

manic wing
#

you can just do bot.get_role

maiden fable
unkempt canyonBOT
maiden fable
#

Thought so

manic wing
#

:p

maiden fable
manic wing
#

sammmmmmmmmmmmmeeee thing

maiden fable
#

Just try it....?

tawdry perch
maiden fable
#

Error?

manic wing
#

discord.utils.get is mainly for name kwarg

maiden fable
#

Show lol

tawdry perch
#
@commands.command(aliases=["hush", "shh", "shhh"])
    async def silence(self, ctx, time: int = None):
        '''Silences the channel for default role'''
        print(self.default)
        role = ctx.guild.get_role(self.default)
        if time is None:
            time = 60 * 10
        else:
            time = time * 60
        print(role.id)
        ...
``` ```print(role.id)
AttributeError: 'NoneType' object has no attribute 'id' ``` but the first print statement gave `776140379442905098`
#

and that is correct role id

slate swan
#

why does the bot command not work

#

begin command

slate swan
#

i just started using bot class

maiden fable
slate swan
#

when i type $begin

tawdry perch
slate swan
#

nothing happens

maiden fable
tawdry perch
#

weird but thx

slate swan
#

any idea why?

maiden fable
#

What's items?

pliant gulch
slate swan
#

a long list of strings

maiden fable
#

Aaaah yes

pliant gulch
#

You need to add process_commands to your on_message

maiden fable
#

Didn't see that

pliant gulch
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

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

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

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

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

Just change the deco to bot.listen()

slate swan
maiden fable
#

@bot.event

slate swan
#

both?

#
    @commands.command()
    async def generuj(self, ctx, role : discord.Role = None):
        code = random_char(15)
        db = sqlite3.connect("database.db")
        cursor = db.cursor()
        cursor.execute("INSERT INTO voucher(code, role_id) VALUES(?,?)", (code, role.id))
        await ctx.send(f"Wygenerowano voucher na {role.mention}\nKod na nia to ``{code}``")
    @commands.command()
    async def odbierz(self, ctx, code):
        db = sqlite3.connect("database.db")
        cursor = db.cursor()
        cursor.execute(f"SELECT code FROM voucher")
        wynik=cursor.fetchall()
        if wynik:
            for kod in wynik:
                if code == wynik:
                    await ctx.send("Odebrales wlasnie role!")

Insert into voucher dont working

#

i have 2

maiden fable
slate swan
#
    @commands.Cog.listener()
    async def on_ready(self):
        print("voucher.py - on")
        cursor.execute("CREATE TABLE IF NOT EXISTS voucher(code STR, role_id INT)")
#
def random_char(y):
       return ''.join(random.choice(string.ascii_letters) for x in range(y))

Random

maiden fable
slate swan
#

oh i didn't see but

#

i have cursor.execute("CREATE TABLE IF NOT EXISTS voucher(code STR, role_id INT)") in command

#

and table is created

lament aurora
#

I have a problem in this code:

connect = False
@client.command()
async def play(ctx,url : str):
    global connect
    voiceChannel = discord.utils.get(ctx.guild.voice_channels,name='γ€Ž 1 γ€Ψ£Ψ΅ΩˆΨ§Ψͺ')
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if not connect:
        await voiceChannel.connect()
        connect = True

@client.command()
async def leave(ctx):
    global connect
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if connect:
        await voice.disconnect()
        connect = False
    else:
        await ctx.send("the bot is not connected in voice Channel.")

he send this error in a terminal:

Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: url is a required argument that is missing.
tawdry perch
#

When I create role how can I make it second highest role in server? ```py
perms = discord.PermissionOverwrite(perm)
mutedrole = await ctx.guild.create_role(name="Muted", permissions=perms)

unkempt canyonBOT
#

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

tawdry perch
#

if I don't know amount of roles in server, it's kind of blind shooting.

slate swan
#

Happens when you get a traceback

#

And why cmd? And not your ides shell

#

What are you using?

#

Why not in its console?

#

Doesnt pycharm have a console

spiral frigate
#

how to send private messages to a user

slate swan
#

Yea i think it does

maiden fable
spiral frigate
peak tapir
#

Hey i ama beginner to making bot. What is the video / web you can recommend

slate swan
spiral frigate
peak tapir
slate swan
#

Run the code in pycharms console

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
peak tapir
#

K

slate swan
peak tapir
#

Yw meaning?

slate swan
spiral frigate
slate swan
#

Code?

slate swan
unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

why is the run in the task

#

Yeah i see that

#

!code aswell

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.

slate swan
#

Did you even add its token???

#

client.run()

#

why is it indented so it is in the task

#

Has a error then

#

You have

[...].now()**..**now(timezone)
And I'm pretty sure timezone is not defined, at least not in the part of code you shared

#

why two dots

#

Remove one dot

#

And define the timezone variable

#

You don't know what defining a variable means?

#

Have you learned Python before starting a bot?

#

Defining a variable is one of the first thing you learn

#

Interesting

#
x = "variable"

This is defining a variable...

#

Probably the first thing you learned, if you learned it

#

So you need to define the timezone

#

Or just remove the timezone part

#

And just use

now = datetime.datetime.now()

#

I can already tell you that the code is definitely not all right

#

hey i can't add channel into a category

#

what arg should i give to category?

#

name or id

#

anyone?

#

What is your code..

#

await ctx.guild.create_text_channel(name= i,category="shop", topic=k)

#

i is a string

#

k too

#

what should i set to category?

#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

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

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

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

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

Note

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

As you can see on the documentation, it requires a CategoryChannel object, and not a string

#

And you can get such an object using get_channel() or discord.utils.get()

#

Thanks

slate swan
#

How do i get channel category object

maiden fable
#

Same way

slate swan
#

Not only a channel object

maiden fable
#

!d discord.CategoryChannel

unkempt canyonBOT
#

class discord.CategoryChannel```
Represents a Discord channel category.

These are useful to group channels to logical compartments.

x == y Checks if two channels are equal.

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

hash(x) Returns the category’s hash.

str(x) Returns the category’s name.
slate swan
#

It returns a TextChannel, StageChannel, CategoryChannel, etc.

#

i have a question. I have heard discord.py will not be updated anymore?

#

is this true?

maiden fable
#

Yes

slate swan
#

someone have a template code of a discord private dm bot?

slate swan
#
import disnake, os, pymongo, datetime
os.system("pip install -U disnake")
from disanke.ext import commands

bot = commands.Bot(command_prefix=commands.when_mentioned_or("."), intents=disnake.Intents.all())


@bot.event
async def on_ready():
  try:
   os.system("cls")
   print(f"Connected to client: {bot.user}")
  except:
    os.system("clear")
    print(f"Connected to client: {bot.user}")


``` Error:

File "main.py", line 1, in <module>
import disnake, os, pymongo, datetime
ModuleNotFoundError: No module named 'disnake'```

#

Then when i take that out it says
No module named pymongo

slate swan
slate swan
#

pip install disnake

#

im using replit, because my partner doesnt have vscode

slate swan
#

At least I don't have to worry about upcoming updates.

slate swan
#

Yh i just figured that out

wanton cipher
#

I was wondering if anyone could help me, how would I get my bot object in a different file, I am trying to make a custom_checks.py file and I need to get the bot so I can get values, example bot.owner_id and so on, how would I do this?

shadow wraith
#

File "beginner.py", line 7
async def ping(ctx):
^
SyntaxError: invalid syntax
for some reason this error pops up when i try to start my bot

#

i used the example from github btw

#

will anyone help me?

outer violet
#

I added the time input and it works well but how would I make it say your timer has ended! (00hr:00m:00s)?

@commands.command()
    async def timer(self, ctx, timeInput):
        try:
            try:
                time = int(timeInput)
            except:
                convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
                time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]

            if time > 86400:
                await ctx.send("I can't do timers over a day long.")
                return
            if time <= 0:
                await ctx.send("Timers don't go into negatives :/")
                return

            if time >= 3600:
                message = await ctx.send(f"⏱️ Remaining time: **{time//3600}hr:{time%3600//60}m:{time%60}s**")
            elif time >= 60:
                message = await ctx.send(f"⏱️ Remaining time: **{time//60}m:{time%60}s**")
            elif time < 60:
                message = await ctx.send(f"⏱️ Remaining time: **{time}s**")

            while True:
                try:
                    await asyncio.sleep(1)
                    time -= 1
                    if time >= 3600:
                        await message.edit(content=f"⏱️ Remaining time: **{time//3600}hr:{time %3600//60}m:{time%60}s**")
                    elif time >= 60:
                        await message.edit(content=f"⏱️ Remaining time: **{time//60}m:{time%60}s**")
                    elif time < 60:
                        await message.edit(content=f"⏱️ Remaining time: **{time}s**")
                    if time <= 0:
                        await message.edit(content="⏱️ Timer ended!")
                        await ctx.reply(f"Your countdown has ended! (**{timeInput}**)")
                        break

                except:
                    break
        except:
            await ctx.send(f"Alright, first you gotta let me know how I'm gonna time **{timeInput}**...")
spiral frigate
#

what's my problem here

    @commands.Cog.listener()
    async def on_member_join(self, member):

        member = member.mention
        guild = member.guild.name
        membercount = member.guild.member_count

        _id = member.guild.id

        welcome = self.collection.find_one({"_id": _id})["welcome"]

        if welcome == None:
            pass
        else:
            embed = disnake.Embed (
                title = f'ΠŸΡ€ΠΈΠ²Π΅Ρ‚ΡΡ‚Π²ΡƒΠ΅Ρ‚ **{guild}**:',
                description = ">>> {welcome}".format(welcome=welcome).format(member=member, guild=guild, membercount=membercount),
                colour = 0x694c5f
            )
            await member.send(embed = embed)

error

  File "O:\Suzuki\cogs\settings.py", line 170, in on_member_join
    guild = member.guild.name
AttributeError: 'str' object has no attribute 'guild'
outer violet
slate swan
#

Can someone help me?

mossy sigil
slate swan
#
  File "d:\Applications\mybot\bot.py", line 31, in <module>
    @client.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'```
maiden fable
#

Remove the brackets

gilded crystal
#

how do i learn

slate swan
slate swan
gilded crystal
slate swan
gilded crystal
#

Yes

slate swan
gilded crystal
#

are there any tutorials i could read

slate swan
# gilded crystal are there any tutorials i could read

Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables

Along the way, you will learn to use Repl.it's built-in database and cr...

β–Ά Play video
undone wyvern
slate swan
#

And use the api reference for any errors or any other stuff like commands

gilded crystal
#

Thanks guys

slate swan
#

2 good tutorials you should watch

slate swan
reef shell
final iron
#

^

slate swan
reef shell
#

you should not recommend this tutorial to beginners shrug

slate swan
#

Never seen a up to date tutorial πŸ€·β€β™‚οΈ

reef shell
#

this one ^

slate swan
#

Never seen it or done it so idk

dusk dust
#

how can i upload an image (without being embed)

slate swan
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
slate swan
#

send takes a file kwarg

spiral frigate
#

how to insert a file here
embed.set_image(url= )

slate swan
#
embed = discord.Embed()
embed.set_image(
    url="attachment://filename.png"
)
image = discord.File("/path/to/filename.png")
await ctx.send(
    embed=embed,
    file=image
)```
spiral frigate
#

it doesn 't work that 's how I wrote:

            welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
            
            embed.set_image(url= f"attachment://{welcome_gif}")
            image = disnake.File(f"resources/{welcome_gif}")
slate swan
#

anyone good at py trying to help me fix this source code I keep getting an error this is an discord py bot btw

#

I'll pay u nitro or sum

slate swan
#

can you tell the code
and error, or what u wanna do with it?

pallid storm
#

anybody has a great tutorial on how to make a discord modmail? from scratch

spiral frigate
# slate swan ```py embed = discord.Embed() embed.set_image( url="attachment://filename.pn...

error

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "O:\Suzuki\cogs\settings.py", line 196, in on_member_join
    await member.send(embed = embed, file=image)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\abc.py", line 1414, in send
    data = await state.http.send_files(
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\http.py", line 376, in request
    raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').

spiral frigate
slate swan
#

show full code

spiral frigate
#
    @commands.Cog.listener()
    async def on_member_join(self, member):

        user = member.mention
        guild = member.guild.name
        membercount = member.guild.member_count

        _id = member.guild.id
        
        welcome = self.collection.find_one({"_id": _id})["welcome"]

        if welcome == None:
            pass
        else:
            embed = disnake.Embed (
                title = f'ΠŸΡ€ΠΈΠ²Π΅Ρ‚ΡΡ‚Π²ΡƒΠ΅Ρ‚ **{guild}**:',
                description = ">>> {welcome}".format(welcome=welcome).format(user=user, guild=guild, membercount=membercount),
                colour = 0x694c5f
            )
            embed.set_thumbnail(url= member.avatar)

            welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
            
            embed.set_image(url= f"attachment://{welcome_gif}")
            image = disnake.File(f"resources/{welcome_gif}")
            await member.send(embed = embed, file=image)
slate swan
#
Traceback (most recent call last):
  File "C:\Python39\lib\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 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\felix\OneDrive\Desktop\1 new Prime\Asylum-src-main\cogs\HelpPaginated.py", line 12, in <module>
    from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Python39\lib\site-packages\discord_components\__init__.py)

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

Traceback (most recent call last):
  File "C:\Users\felix\OneDrive\Desktop\1 new Prime\Asylum-src-main\main.py", line 153, in <module>
    client.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Python39\lib\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 'cogs.HelpPaginated' raised an error: ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Python39\lib\site-packages\discord_components\__init__.py) ``` im trying to turn this py bot on and i keep getting errors
#

it's telling you that
the COGS you are trying to load is having error importing InterationType

#
@bot.command()
async def lock(ctx):
    for channel in ctx.guild.channels:
        try:
            await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
        except:
            pass

Hi, I can't get the bot to interact with all the server channels

#

help me please

spiral frigate
slate swan
#

try removing
from discord_components import InteractionType
from cogs file
@slate swan

slate swan
#

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "wl" is not found

#

@slate swan this right?

spiral frigate
dapper cobalt
# slate swan

You should use the client.command() decorator, not the client.event; since you're making a command.

slate swan
#

how i can do it ?

dapper cobalt
slate swan
#

hi

slate swan
dapper cobalt
slate swan
slate swan
#

sudo apt install python3

slate swan
slate swan
outer violet
slate swan
slate swan
#

@slate swan did you check all the functions of cogs file?

jade tartan
#

someone help

#

my error is at the bottom

slate swan
#

well lol

#

unexpected indent

slate swan
# spiral frigate help me please

i found this stuff on stackoverflow
it is- sending local image as embed in d.py
but you can customise it for sending other things
try it

    file = discord.File("output.png")
    e = discord.Embed()
    e.set_image(url="attachment://output.png")
    await ctx.send(file = file, embed=e)```
#

this is an error no one should come here with (indents)

slate swan
mossy sigil
slate swan
#

lol

#
    elif not time:
        await ctx.send("You must mention a time!")
    else:
           if not reason:
                reason="No reason given"
    try:
        seconds = time[:-1]
            duration = time[-1]
```yo what the
#
@bot.command()
async def lock(ctx):
    for channel in ctx.guild.channels:
        try:
            await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
        except:
            pass

Hi, I can't get the bot to interact with all the server channels

#

leave ctx in the line where you set the permissions

#

ctx.channel only refers to one channel (where you invoked the command)

#

install discord to python3.9

#

and it's not client.Bot, just client

#

pip3.9 install discord

#

wait that's probably not the command

#

yes

#

then completely restart VS Code

#

I think so

#

nice

slate swan
#

ban_member is not a permission name

#

probably ban_members?

edgy lion
#
                        ignore_roles_as_roles = []
                        for role in ignore_roles:
                            i = message.guild.get_role(int(role[0]))
                            ignore_roles_as_roles.append(i)

                            print(ignore_roles_as_roles)```

Print:
```py
[<Role id=903714996188479499 name='Twitch'>]
[<Role id=903714996188479499 name='Twitch'>]```


why are the same roles appended even though they are two different ones (in the datebase)
https://cdn.discordapp.com/attachments/890585578465271851/906649239596195900/unknown.png
slate swan
#

Is there a sleep command I can use in interactions because time.sleep and asyncio.sleep both throw errors

#

They work

#

But throws an error

#

Which I can’t handle

velvet crest
slate swan
# velvet crest Send the error ur gttin
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 424, in defer
    await adapter.create_interaction_response(
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

i have debugged it to be time.sleep

#

thats causing it

velvet crest
#

Also cchrck ur token its invalid

dapper cobalt
#

And also you revealed your token.

velvet crest
slate swan
velvet crest
#

also are u responding to the interaction after wards?

slate swan
# velvet crest Dont use time.sleep it will block ur code use asycio.sleep
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="\u25b6", custom_id="PLAYBUTTON")
    async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
        
        if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
            
            message = await interaction.channel.send("playing! " + interaction.user.mention)
            
            await asyncio.sleep(5)
            await message.delete()
slate swan
velvet crest
edgy lion
oak falcon
#

there is dropdown in discord which is discord.ui.Select, what about the other one where options are in separate rows as buttons - what can I use to build this ui selection list?

waxen granite
#

discord.errors.InvalidArgument: file parameter must be File what is this error?

edgy lion
#
                        ignore_roles_as_roles = []
                        for role in ignore_roles:
                            i = message.guild.get_role(int(role[0]))
                            ignore_roles_as_roles.append(i)

                            print(ignore_roles_as_roles)```

Print:
```py
[<Role id=903714996188479499 name='Twitch'>]
[<Role id=903714996188479499 name='Twitch'>]```


why are the same roles appended even though they are two different ones (in the datebase)
https://cdn.discordapp.com/attachments/890585578465271851/906649239596195900/unknown.png
manic wing
dusk dust
#

anyone can send add_role example?

lucid verge
#

Could someone help me, it won't allow me to make more than one embed command.

When I execute one command it works but the other embed doesn't.

#
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('What are you doing step jay'))
    print('obama')
    
@client.event
async def on_message(message):
    if message.content.startswith('.kade'):
        embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
        embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
        embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
        await message.channel.send(embed=embedVar)

@client.event
async def on_message(message):
    if message.content.startswith('.week'):
        embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
        embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
        embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
        await message.channel.send(embed=embedVar)



client.run('TOKEN')
#

heres the code

slate swan
#

use @quaint axle.command()

lucid verge
#

wdym

#
@client.command
async def week(ctx):
        embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
        embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
        embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
        await ctx.channel.send(embed=embedVar)
#

like this?

slate swan
#

!char-info πŸ›‘

#

!charinfo πŸ›‘

unkempt canyonBOT
slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 159, in quit
    self.stop()
TypeError: 'Button' object is not callable```
unkempt canyonBOT
#

Hey @slate swan!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

slate swan
#

I did a currency bot few years ago, what do you need help with?

#

Ok

#

I’ll send my code

#

You can modify it to your needs because my code was pretty dumb

#

It worked though(without databases)

#
@bot.command(aliases=["balance"])
async def bal(ctx, user: discord.Member = None):
  with open("moneys.json", "r") as file:
    balance = json.load(file)
    
  if user is not None:
    mention = user
    image = user
    if str(user.id) in balance:
      print("user in dict")
    else:
      balance[str(user.id)] = 0
  else:
    mention = ctx.author
    image = ctx.author
    if str(ctx.author.id) in balance:
      print("user in dict")
    else:
      balance[str(ctx.author.id)] = 0

  with open("moneys.json", "w") as file:
    json.dump(balance, file)

  embed = discord.Embed(title=f"__account__", description="")
  embed.set_author(name=mention, icon_url=mention.avatar_url)
  embed.add_field(name="noice bucks", value=f":noice:: {balance[str(mention.id)]}")
  await ctx.send(embed=embed)```
#

this was my balance code

#
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def add_money(ctx, user: discord.Member, amount: int):
  with open("moneys.json", "r") as file:
    balance = json.load(file)

  if str(user.id) in balance:
    balance[str(user.id)] += amount
  else:
    balance[str(user.id)] = amount

  if amount == 1:
    s = ""
  else:
    s = "s"
  channel = bot.get_channel(769675445368258581)
  embed = discord.Embed(title="money added", description=f"{amount} noicebuck{s} were added to {user.mention}'s balance")
  await channel.send(embed=embed)
  with open("moneys.json", "w") as file:
    json.dump(balance, file)
    
  await ctx.send(f"added {amount} noice buck{s} to {user.mention}'s balance")
``` add money command
#
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def remove_money(ctx, user: discord.Member, amount: int):
  with open("moneys.json", "r") as file:
    balance = json.load(file)
    
  if amount == 1:
    s = ""
  else:
    s = "s"

  if str(user.id) in balance:
    if amount > balance[str(user.id)]:
      await ctx.send(f"cant remove noice bucks from {user.mention}, because {user.mention} would be in dept")
    else:
      balance[str(user.id)] -= amount
      await ctx.send(f"removed {amount} noice buck{s} from {user.mention}'s account")
      channel = bot.get_channel(769675445368258581)
      embed = discord.Embed(title="money removed", description=f"{amount} noicebuck{s} were removed from {user.mention}'s balance")
      await channel.send(embed=embed)
  else:
    balance[str(user.id)] = 0
    await ctx.send(f"cant remove noice bucks from {user.mention}, because {user.mention} would be in dept")

  with open("moneys.json", "w") as file:
    json.dump(balance, file)
``` remove money command
#
@bot.command()
async def shop(ctx):
  with open("shop.json", "r") as file:
    shop = json.load(file)
  embed = discord.Embed(title="shop", description="use !buy <item name> <amount(optional)>")
  if not shop:
    embed.add_field(name="shop empty", value="sorry, the shop is empty, wait for mods to add item")
    await ctx.send(embed=embed)
    return
  else:
    name = [x["name"] for x in shop.values()]
    price = [x["price"] for x in shop.values()]
    desc = [x["desc"] for x in shop.values()]
    for x in range(0, len(shop)):
      print(name)
      embed.add_field(name=f":noice:{price[x]} - {name[x]}",
                      value=f"{desc[x]}")
  await ctx.send(embed=embed)
``` shop command
#
@bot.command()
async def buy(ctx, item, amount : int = None):
  with open("moneys.json", "r") as file:
    balance = json.load(file)
  with open ("shop.json", "r") as file:
    shop = json.load(file)
  with open("inv.json", "r") as file:
    inv = json.load(file)
  itemb = "item"
  if item in shop:
    if str(ctx.author.id) in balance:
      if str(ctx.author.id) in inv:
        pass
      else:
        inv[str(ctx.author.id)] = {}
      if shop[str(item)]["price"] > balance[str(ctx.author.id)]:
        await ctx.send(f"not enough money to buy {item}")
        return
      else:
        if amount is not None:
          if shop[str(item)]["price"] * amount > balance[str(ctx.author.id)]:
            await ctx.send("not enough money to buy items")
            return
          else:
            total = amount
        else:
          total = 1
        balance[str(ctx.author.id)] -= shop[item]["price"] * total
        price = shop[item]["price"]
        if item in inv[str(ctx.author.id)]:
          inv[str(ctx.author.id)][item] += total
        else:
          inv[str(ctx.author.id)][item] = total
        await ctx.send(f"bought {total} {item} for {price * total} noice bucks")
        
    else:
      balance[str(ctx.author.id)] = 0
      await ctx.send(f"not enough money to buy {item}")
  else:
    await ctx.send(f"cant find the item: {item}")

  with open("moneys.json", "w") as file:
    json.dump(balance, file)
  with open("inv.json", "w") as file:
    json.dump(inv, file)``` buy command
#

yes

#

this is the python discord srver

#
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def add_item(ctx, name, price : int, role : discord.Role = None, *, desc):
  with open("shop.json", "r") as file:
    shop = json.load(file)
  if name in shop:
    await ctx.send("item allready exists")
    return
  else:
    shop[name] = {}
    shop[name]["name"] = name
    shop[name]["price"] = price
    shop[name]["desc"] = desc
    if role is not None:
      shop[name]["role"] = str(role.id)
      shop[name]["desc"] = "gives role " + role.mention + ". " + desc
      rolem = "gives role " + role.mention + ". "
    else:
      shop[name]["desc"] = desc
      rolem = ""
    embed = discord.Embed(title="item created", description="")
    embed.add_field(name=f":noice:{price} - {name}", value=f"{rolem}{desc}")
    await ctx.send(embed=embed)
    channel = bot.get_channel(769675445368258581)
    await channel.send(embed=embed)
    
  with open("shop.json", "w") as file:
    json.dump(shop, file)
``` add item ciommand
#

yes

#

but the .json files are seperate

#
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def remove_item(ctx, name):
  with open("shop.json", "r") as file:
    shop = json.load(file)
  if name in shop:
    await ctx.send(f"{name} has been deleted")
    embed = discord.Embed(title="item removed", description="")
    embed.add_field(name=f":noice:{shop[name]['price']} - {shop[name]['name']}", value=f"{shop[name]['desc']}")
    channel = bot.get_channel(769675445368258581)
    await channel.send(embed=embed)
    del shop[name]
  else:
    await ctx.send("item not found")

  with open("shop.json", "w") as file:
    json.dump(shop, file)
``` remove item command
#
@bot.command()
@commands.cooldown(1, 30, commands.BucketType.user)
async def gamble(ctx, amount : int):
  with open("moneys.json", "r") as file:
    balance = json.load(file)
  if str(ctx.author.id) in balance:
    pass
  else:
    balance[str(ctx.author.id)] = 0
    
  if balance[str(ctx.author.id)] < amount:
    message = await ctx.send("cant bet amount because balance is to low")
    time.sleep(4)
    await message.delete()
  else:
    balance[str(ctx.author.id)] -= amount
    wa = random.randint(0, 10)
    lotteryc = random.randint(0, 10000)
    balance[str(ctx.author.id)] += amount * wa
    if wa == 0:
      message = await ctx.send("looks like you didnt win anything *sad trombone*")
      time.sleep(4)
      await message.delete()
    else:
      if wa == 1:
        message = await ctx.send("you won your money back!!! woohooo!!")
        time.sleep(4)
        await message.delete()
      else:
        message = await ctx.send(f"you won {amount * wa} noicebucks!!! nice!!!")
        time.sleep(4)
        await message.delete()
      if lotteryc == 69:
        await ctx.send(f"{ctx.author.mention} YOU HAVE WON THE LOTTERY!!!!! OF 1000000000 NOICEBUCKS!!!")
        balance[str(ctx.author.id)] += 1000000000
      print(lotteryc)
    with open("moneys.json", "w") as file:
      json.dump(balance, file) 
    

@gamble.error
async def gamble_error(ctx, error):
  if isinstance(error, commands.errors.CommandOnCooldown):
    await ctx.send(error)
  else:
    raise error
``` gamble command (with error handeling)
#
@bot.command()
async def use(ctx, item):
  with open("inv.json", "r") as file:
    inv = json.load(file)
  with open("shop.json", "r") as file:
    shop = json.load(file)
                    
  if str(ctx.author.id) in inv:
    if item in inv[str(ctx.author.id)]:
      if not shop[item]["role"]:
        pass
      else:
        role = get(bot.get_guild(ctx.guild.id).roles, id=int(shop[item]["role"]))
        await ctx.author.add_roles(role)
      if inv[str(ctx.author.id)][item] > 1:
        inv[str(ctx.author.id)][item] -= 1
        await ctx.send(f"1 {item} used")
      else:
        del inv[str(ctx.author.id)][item]
        await ctx.send(f"1 {item} used")
    else:
      await ctx.send("item not found")
  else:
    await ctx.send("item not found")
  with open("inv.json", "w") as file:
    json.dump(inv, file)``` use command
#

and thats all i had

#

plus some extra commands that arent important

#

a stats command warn command etc

#

for each json file just put {} in them

#

and the bot should work fine

#
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def stats(ctx, user: discord.Member = None):
  with open("moneys.json", "r") as file:
    balance = json.load(file)  
  with open("warns.json", "r") as file:
    warns = json.load(file)

  if user is not None:
    userv = user
    if str(user.id) in balance:
      pass
    else:
      balance[str(user.id)] = 0
    if str(user.id) in warns:
      amountW = warns[str(user.id)]
    else:
      amountW = 0
  else:
    userv = ctx.author
    if str(ctx.author.id) in balance:
      pass
    else:
      balance[str(ctx.author.id)] = 0
    if str(ctx.author.id) in warns:
      amountW = warns[str(ctx.author.id)]
    else:
      amountW = 0

  with open("moneys.json", "w") as file:
    json.dump(balance, file)
  sort = sorted(balance, key=balance.get, reverse=True)
  embed=discord.Embed(title=f"__stats__", description="")
  embed.set_author(name=userv, icon_url=userv.avatar_url)
  embed.add_field(name="noice bucks", value=f":noice:: {balance[str(userv.id)]}")
  embed.add_field(name="places on leaderboards", value=f"noicebucklb: placed {sort.index(str(userv.id)) + 1}")
  embed.add_field(name="warns", value=f"{amountW}/3 warns")
  embed.add_field(name="top role", value=f"{userv.top_role.mention}")
  embed.set_thumbnail(url=userv.avatar_url)
  await ctx.send(embed=embed)
#

this may not work so moify it a bit

#

you wont have the warn file

#

so the warn bit wont work

#

Wdym

#

I have a help command with the bot

#

If u want that

#

that has all the commands that i had o my bot

#

It’s has the syntax, args and stuff

#

There’s no role in that β€œβ€

bitter depot
#

You also need to dedent the @bot.command()

slate swan
#

Pasting directly from discord may lead to some problems

#

So fix that before doing anything

#

Have you removed the indent block?

slate swan
slate swan
#

K sick

#

And remove Harckepy himself there and just add the roles you want to be able to run the command

#

I will throw an error if there is a role that isn’t in the server

#

You’ve removed a command and a decorator

#

How tf do u do that

#

Hey, I'm trying to get a wikipedia bot for my school discord server that can be able to respond to computer science and math questions primarily. The best I could do was a bot that could do math which isn't particularly helpful. Does anyone have source code for this purpose?

slate swan
#

No not for doing math, that's easy. I'll post the one I made in a lil bit. For answering questions by posting stuff from wikipedia

#

so query?

#

like !question question

#

and it will answer uestion from wikipeida

#

If for example I asked. "Tell me what Computer Science is" Then I could get a result accordingly

torpid dew
#

Hi, I am trying to make a calculator bot, this is one command not finished, I am stuck on how to make await and outside function while including def check(msg1)

@client.command()
async def calc(ctx):
  await ctx.send('What type of calculation do you want to do? **addition** > βŸͺ`add`⟫, **subtraction** > βŸͺ`sub`⟫, **division** > βŸͺ`div`⟫, **multplication** > βŸͺ`mult`⟫, **absolute value** > βŸͺ`abs`⟫, **square root** > βŸͺ`sqr`⟫, **squaring** > βŸͺ`sq`⟫')
  def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and \
        msg.content.lower() in ["add", "sub"]
  msg = await client.wait_for("message", check=check)
  if msg.content.lower() == 'add':
    await ctx.send('What is your equation? Do 𝒙 + *y* Only 2 numbers adding.')
    def check(msg1):
      ad = msg1.split(' ')
      add = int(msg1[0])
      addd = int(msg1[-1])
      await ctx.send(add + addd)
slate swan
#
import discord
from asyncio import sleep
import os
from discord.ext import commands
import random
import math
import keep_alive
from dotenv import load_dotenv


load_dotenv()


client = commands.AutoShardedBot(commands.when_mentioned_or('Please '))


@client.event
async def on_ready():
    print('Ready.')

def Add(n: float, n2: float):
    return n + n2

def sub(n: float, n2: float):
    return n - n2

def rando(n: int, n2: int):
    return random.randint(n, n2)

def div(n: float, n2: float):
    return n / n2

def sqrt(n: float):
    return math.sqrt(n)

def mult(n: float, n2: float):
    return n * n2


@client.command()
async def add(ctx, x: float, y: float):
    try:
        result = Add(x, y)
        await ctx.send(result)

    except:
        pass

@client.command()
async def subtract(ctx, x: float, y: float):
    try:
        result = sub(x, y)
        await ctx.send(result)

    except:
        pass

@client.command()
async def Random(ctx, x: int, y: int):
    try:
        result = rando(x, y)
        await ctx.send(result)

    except:
        pass

@client.command()
async def divide(ctx, x: float, y: float):
    try:
        result = div(x, y)
        await ctx.send(result)

    except:
        pass

@client.command()
async def muliply(ctx, x: float, y: float):
    try:
        result = mult(x, y)
        await ctx.send(result)

    except:
        pass

@client.command()
async def squareroot(ctx, x: float):
    try:
        result = sqrt(x)
        await ctx.send(result)

    except:
        pass

keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
#

this just handles simple math problems

#

k

#

Pls add 2 2, and it adds them

torpid dew
#

ok

slate swan
#

so i would use an on_message event and wikipedia api

#

getting the text between tell me what and is

#

and querying it through the api

#

heres the api link

#

sending wikipedia.summary("Wikipedia") should work

torpid dew
slate swan
#

i need help

slate swan
#

i have a disc bot but i want only me to use them how do i do that?

#

like !ban and kick

#

only for me

#

you cn do a check for roles, user or permissions

#

which one do you want to use?

#

check for roles

#
@commands.has_any_role("Role name")
``` add this below @native granite
#

oops

#

pinged someone

#

someone have a code of private dm bot?

slate swan
slate swan
slate swan
#

yes

#

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

slate swan
#

thats a command that is used in dm

#

what does this mean

slate swan
slate swan
slate swan
#

okay

#

to the command user

unkempt canyonBOT
#

Hey @slate swan!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

slate swan
#

Ignoring exception in command help:
Traceback (most recent call last):
File "main.py", line 224, in help
helpselect = msg[2]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 262, in help
await bot.say("/w help search\n/w help display\n/w help lang\n/w help random\n/w help about")
AttributeError: 'Bot' object has no attribute 'say'

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'say'
Ignoring exception in command help:
Traceback (most recent call last):
File "main.py", line 227, in help
await bot.say("/w search 'term' - searches wikipedia on given term")
AttributeError: 'Bot' object has no attribute 'say'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 262, in help
await bot.say("/w help search\n/w help display\n/w help lang\n/w help random\n/w help about")
AttributeError: 'Bot' object has no attribute 'say'

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

#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'say

slate swan
#

did you just send in your bot in a public server

#

where anyone can troll u

#

good

magic stump
#
@bot.command()
async def rps(ctx, msg):
    print("s")

    Rock = "R"
    Sissors = "S"
    Paper = "P"

    list = 'Rock',"Sissors","Paper"

    random_list = 1
    list = "".join(random.sample(list,random_list))

    print(list)

    if msg == list:
        await ctx.send("Draw")

    elif 'Rock' == msg:
        if list == 'Sissors':
            await ctx.send("You win! Bot selected **Sissors**")
        else:
            await ctx.send("Losser")
    elif msg == "Sissors":
        if list == 'Paper':
            await ctx.send("You win! Bot selected **Paper**")
        else:
            await ctx.send("Losser")
    elif msg == "Paper":
        if list == 'Rock':
            await ctx.send("You win! Bot selected **Rock**")
        else:
            await ctx.send("Losser")

    else:
        print("nie dziala")```How to do when select choose such a word, for example
RoCk
slate swan
slate swan
#

what am I doing wrong?

#

did you define commands.Bot/discord.Client as Client or client?

#

should be lowercase

#

also, add_reaction() should be awaited

#

if someone try a command and they dont have that role how can i make it so the bot ads a reaction

crystal wind
#

Hey I have a question, is it possible for discord to convert an argument into a numpy array directly? Or I have to convert the string?

blissful crane
#
import discord
from discord.ext import commands
import disgames
from disgames.mixins import Hangman

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

bot.add_cog(Hangman(bot))

error: Traceback (most recent call last): File "C:\Users\HiTech\Desktop\hhh.py", line 8, in <module> bot.add_cog(Hangman(bot)) File "C:\Users\HiTech\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 505, in add_cog raise TypeError('cogs must derive from Cog') TypeError: cogs must derive from Cog, the Hangman class is subclassed from commands.Cog tho ```py
import discord
from discord.ext import commands

class Hangman(commands.Cog):
"""
Hang man command
"""

def __init__(self, bot):
    self.bot = bot
I am loosing my mind over this
supple thorn
blissful crane
#

yes

#

i imported the cog and then used bot.add_cog

slate swan
#

if someone try a command and they dont have that role how can i make it so the bot ads a reaction

blissful crane
#

the top piece of code is the main file

blissful crane
supple thorn
#

Thats probably better

#

Oh a reaction

#

Thought that was add role

slate swan
#

im not saying theres an error but how do i make it so it reacts when they dont have the role

blissful crane
blissful crane
supple thorn
#

I really dont know any other way

blissful crane
#

load_ext basically just imports the cog and executes the setup function, which is basically what i am doing

blissful crane
#

but for some reason it seems to think that Hangman is not a cog

slate swan
#

how do i make a ping command?

blissful crane
#

bot.latency returns the bot's ping in seconds, multiply it by 1000 to get the ping in milliseconds

slate swan
#

how do i make an embed with all my commands?

blissful crane
pure basin
#

how to use discord.ui.button? keeps telling me discord has no ui

pliant gulch
#

You need to be using the master branch version of discord.py (from the github repo)

#

Using the pypi package will not work as its still on v1.7.3

#

You need v2.0.0a

acoustic ermine
#

Is it possible to be able to get the content of someone’s status

hard trail
#

@bot.command()
async def coinflip(ctx):
  if random.choice(determine_flip) == 1: 
    
      myEmbed9 = discord.Embed(title="A COIN HAS BEEN FLIPPED!", 
      description = f"{ctx.author.mention} has got **Heads**!")
      await ctx.send(embed=myEmbed9)

  else: 
    
      
      myEmbed10 = discord.Embed(title="A COIN HAS BEEN FLIPPED!", d 
      description = f"{ctx.author.mention} flipped **Heads**")
      await ctx.send(embed=myEmbed10)```
#

So I made a coin flip command

#

and everytime I do it I keep flipping heads

#

I've been spamming coinflip and it's not working

supple thorn
#

Im just asking

boreal ravine
#

@blissful crane your supposed to add that in your cog file not main file

hard trail
slate swan
boreal ravine
#

.say isnt an attribute anymore

#

that was from like 2016

hard trail
#

I'm so stupid

#

I really need some sleep

#

Thanks

torpid dew
#

Why does it say [pyflakes] local variable 'note' defined in enclosing scope on line 22 referenced before assignment in ```python
@client.command()
async def note(ctx, message=None):
note = (note[5:-1])

outer violet
#

Can someone help?


@commands.command(name='createpoll', aliases=['poll'])
    async def create_poll(self, ctx, question: str, *options):
        if len(options) > 10:
            await ctx.send("You can only supply a maximum of **10** options.")

        else:
            embed = discord.Embed(
                title="New poll",
                description=question,
                color=ctx.author.color,
                timestamp=datetime.utcnow()
            )
            embed.add_field(name="Options", value="\n".join([f"{numbers[idx]} {option}" for idx, option in enumerate(options)]), inline=False)
            embed.set_footer(text="React to cast a vote!")
            await ctx.send(embed=embed)

            for emoji in numbers[:len(options)]:
                await message.add_reaction(emoji)
torpid dew
outer violet
boreal ravine
torpid dew
boreal ravine
#

merely a typo

boreal ravine
torpid dew
#
import discord
import random
import json
import requests
from discord.ext import commands


TOKEN = 'My token'
intents = discord.Intents.default()

client = discord.Client()


client = commands.Bot(command_prefix=".")

@client.event
async def on_ready():
  await client.change_presence( activity=discord.Game('.help'))
  print('Bot is ready.')

@client.command()
async def note(ctx, message=None):
  note = (note[5:-1])
#

havent finished

outer violet
boreal ravine
outer violet
#

Alr

torpid dew
#

k

#

ill try

#

thanks

slate swan
#

I'm also having a similar issues with reaction emojis except I'm making an embedded buttons page and am having trouble checking the user's reaction

#

Here's how the embed page looks like

boreal ravine
#

whats wrong?

slate swan
#

I'm unable to get my bot the edit the page when I react with one of the added emojis

boreal ravine
#

hm

#

you made it send a message

slate swan
#

I tried checking the reaction emoji with reaction == [emoji] and user.reaction == [emoji] but it doesn't help

boreal ravine
#

not edit a message

slate swan
#

Oh

#

I forgot to change that but I'll edit it rn

boreal ravine
#

!d discord.Message.edit

unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
slate swan
#

Unfortunately, that didn't work

mortal dove
#

can commands.Bot() take a list as a valid value for command_prefix?

loud junco
#

replit is not downloading discord
what do i do in the shell

slate swan
#

yes

loud junco
#

thanks

mortal dove
#

TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not list Cause I'm currently getting this when doing some stuff I probably shouldn't be doing with prefixes

loud junco
#

replit is rigged
i cant import discord

slate swan
mortal dove
#

yup

#

want me to send the code or nah

slate swan
#

nah , when you return the value , add (client , message) to it

#
async def get_prefix(bot, message):
    extras = await prefixes_for(message.guild) # returns a list
    return commands.when_mentioned_or(*extras)(bot, message)
#

just an example

mortal dove
#

ah I'm not doing it that way
Much messier

slate swan
#

owh what do you have?

mortal dove
#

in the end it boils down to

guild_prefs=cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchone()
if any([message.content.startswith(prefix) for prefix in guild_prefs]): 
  await bot.process_commands(message)
#

also realizing code is shit

#

hang on, I'm just retarder

slate swan
#

so , in an on_message event?

eager pawn
slate swan
#
@commands.command()
    async def hug(self, ctx, ):
        response = requests.get("https://api.nekos.fun:8080/api/hug")
        hug = response.json
        embed=discord.Embed(title="Hug", color=0x109319)
        embed.set_image(url=f"hug['image']")
        embed.set_footer(text=f"Requested by {ctx.author.display_name}")
        await ctx.send(embed=embed)
SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)
mortal dove
#

but yes in an event

slate swan
eager pawn
slate swan
#

what do you mean

mortal dove
#

Guild-specific prefixes

#
@bot.event
async def on_message(message):
    if message.author.bot or message.guild==None:
        return

    await message.channel.send(cur.execute("SELECT * FROM prefixes").fetchall())
    guilds=[int(pack[0]) for pack in all_packs]
    await message.channel.send(f"GUILDS: {guilds}")

    if message.guild.id not in guilds:
        cur.execute(
            f"INSERT INTO prefixes VALUES (?, ?)", (
                message.guild.id, "['@copper leaf ', 'c!']"
            )
        )
        await message.channel.send("Prefixes: "+str(cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchall()))
        await bot.process_commands(message)
        return
    
    guild_prefs=cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchone()

    # If the message starts with any of the guild's prefixes.
    if any([message.content.startswith(prefix) for prefix in guild_prefs]): 
        await bot.process_commands(message)
``` ugly ik, don't mention it
slate swan
eager pawn
slate swan
#

ohh alright ima try that!

slate swan
slate swan
eager pawn
slate swan
#

when i use the command it happens

#
 @commands.command()
    async def hug(self, ctx, ):
        response = requests.get("https://api.nekos.fun:8080/api/hug")
        hug = response.json
        embed=discord.Embed(title="Hug", color=0x109319)
        embed.set_image(url=f"{hug['image']}")
        embed.set_footer(text=f"Requested by {ctx.author.display_name}")
        await ctx.send(embed=embed)
#

response.json() it mustbe

#

ima try that too

eager pawn
#

gl

slate swan
#

doesnt work

eager pawn
#

error?

slate swan
#
SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)')))
@commands.command()
    async def hug(self, ctx, ):
        response = requests.get("https://api.nekos.fun:8080/api/hug")
        hug = response.json()
        embed=discord.Embed(title="Hug", color=0x109319)
        embed.set_image(url=f"{hug['image']}")
        embed.set_footer(text=f"Requested by {ctx.author.display_name}")
        await ctx.send(embed=embed)
shadow wraith
#

oh wait

slate swan
#

that space.

shadow wraith
#

nah its not a ssl certificate issue

slate swan
#

yeah i think so

#

ima try to remove space

shadow wraith
#

and dont forget the comma

#

and also if u use visual studio code in the bottom left you can change your version but if you started your bot fine then your prob using the right verision

slate swan
#

im using idle

shadow wraith
#

yes, idle 3.9.5 or something?

slate swan
#

πŸ’€

#

wait bruh

shadow wraith
#

πŸ’€

slate swan
#

IDLE Shell

#

im a hamburger

shadow wraith
#

check what version ur on on idle shell

eager pawn
#

eh idle shell is fine

slate swan
#

im lazy to download anything

eager pawn
#

the reason i dont use it is because pip keeps saying "oH dIsCorD nOt fOuNd"

slate swan
#

same for me

shadow wraith
#

lol

eager pawn
shadow wraith
#

use pip3 😎

slate swan
eager pawn
shadow wraith
#

wait what i use it

slate swan
#

imagine haiving 4 versions of py installed

shadow wraith
slate swan
shadow wraith
#

my oldest one has to be 2.7

slate swan
#

2.7 and 3.8 was preinstalled since i use linux

shadow wraith
#

and then i realized i had to change my version lmfao in the bottom left

slate swan
#

how can i test to see if my bot is streaming? the strings im using clearly arent working and ive experimented with many including elif member.activity.type == ActivityType.streaming:

slate swan
#

bro wait 1 minute im researching how to check version because i never did i think πŸ’€

slate swan
#

when you try to get the cogs from a folder

shadow wraith
#

havent tried cogs in a while

slate swan
slate swan
#

3.10.0

slate swan
#

or it would be written on the top of idle

shadow wraith
#

nub

slate swan
#

alr

#

3.10 is still not too perfect to work with everything

#

you called me nub 😭 πŸ”ͺ πŸ’€ 😭

shadow wraith
slate swan
#

you forgor

shadow wraith
#

k but lets be a lil serious

slate swan
#

alright im installing 3.9

#

3.9.8?

#

can u guys move to another channel or something cuz im trying to get some help for my discord bot which is literally the name of the channel. cant do that when its being filled by people having a dispute about which version of python they have installed.

#

cry about it haha!

#

jk jk

#

alr

#

how can i test to see if my bot is streaming? the strings im using clearly arent working and ive experimented with many including elif member.activity.type == ActivityType.streaming:

boreal ravine
#

hm

#

!d discord.ActivityType.streaming

unkempt canyonBOT
shadow wraith
#

i used copilot in my discord bot and when i tried doing a calculator command copilot just did "await ctx.send("RICKROLL LINK")"

slate swan
boreal ravine
boreal ravine
slate swan
pliant gulch
#

Everything you see on the docs should be updated for the master branch

#

v2.0.0a

boreal ravine
slate swan
pliant gulch
#

Otherwise you manually need to change the docs branch to master

boreal ravine
slate swan
#

alright and another question

boreal ravine
#

yes?

slate swan
#

using premium_since is there any way i can dictate how long a user has been boosting a server for to coadherse it to its proper badge? something seemingly like "if boosting_for_1_month: boost = '1MonthBoost' , if boosting_for_6_months: boost = '6MonthBoost' "

boreal ravine
slate swan
#

obviously formatted properly, but thats just to get the idea of what im after

boreal ravine
#

hm

#

!d discord.Member.premium_since

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC when the member used their β€œNitro boost” on the guild, if available. This could be None.

boreal ravine
#

well it returns a datetime object so yes you can do something like that

slate swan
#

wouldnt that mean i have to apply each badge to a specific date?

#

im not very experienced with dt thats why im asking lol

pliant gulch
#

You won't need to check for a specific date, you will just need to check the months part

slate swan
spiral frigate
#

I want to upload a file to

embed.set_image(url= )
```. but I did not try to get out like this:

```py
            embed = disnake.Embed (
                title = f'ΠŸΡ€ΠΈΠ²Π΅Ρ‚ΡΡ‚Π²ΡƒΠ΅Ρ‚ **{guild}**:',
                description = ">>> {welcome}".format(welcome=welcome).format(user=user, guild=guild, membercount=membercount),
                colour = 0x694c5f
            )
            embed.set_thumbnail(url= member.avatar)

            welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
            
            image = disnake.File(f"resources/{welcome_gif}")

            embed.set_image(url= f"attachment://{welcome_gif}")
            
            await member.send(embed = embed, file=image)
pliant gulch
# slate swan how might i do this

Construct a datetime.timedelta object, pass in the days representing the months e.g 6months -> 182 ish days then add the timdelta object you just created to the premium_since datetime, and check if its equal or before datetime.datetime.now()

slate swan
#

yikes

pliant gulch
#

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

there we go lol

spiral frigate
# boreal ravine did it send?

no
error

  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "O:\Suzuki\cogs\settings.py", line 194, in on_member_join
    await member.send(embed = embed, file=image)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\abc.py", line 1414, in send
    data = await state.http.send_files(
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\http.py", line 376, in request
    raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').
boreal ravine
#

hm

viral plume
#

?

slate swan
viral plume
#

just write a for loop

slate swan
#

could that work? im probably wrong

pliant gulch
#

It wouldn't do what you want it to do

viral plume
#

variable

hollow palm
#

For what

viral plume
#

variable

#

value

hollow palm
#

What do you mean

viral plume
#

??

slate swan
#

this is against tos

#

and can get u sued by youtube

viral plume
#

no no no i meant while loop

pliant gulch
#

You need to construct the timedelta which you are doing, then you actually need to add it to premium_since and check if that is less than or equal to datetime.datetime.now()

viral plume
#

OMGGGG

viral plume
#

NOOOOO

slate swan
#

bots bypass the ad system on youtube and a whole lot of other regulations

#

thats why groovy was shut down alongside many other music bots

viral plume
#

YOUTUBE NOOOOO IM GONNA SUE YOTUTUBER\

slate swan
#

ok fine lol, take a court case i guess, since u wanna be sarcastic about it

viral plume
#

oh sorry emoji tos

hollow palm
slate swan
viral plume
#

sorry im not america what ius court

#

Is this java

slate swan
# hollow palm alright thanks for the heads up

realistically, youtube doesnt have authorization to see which user is trafficing their website, so if anything theyd have to go through discord, and discord doesnt release that sort of information, as long as youre not reported, youll be fine

viral plume
#

for i in range (?)

#

???

#

objest oriented program?

#

ooh sorry this is not java

#

bye

#

java

#

like the snake

#

see

#

coffee

#

amin

pliant gulch
#

And directly, in the Youtubes ToS it says not to bot them

#

Its not so much the "ad system" being bypassed

#

And realistically I doubt you'd be sued for a music bot, rather a C&D

slate swan
#

true

pliant gulch
#

That's what groovy got, and that's what got it shutdown

viral plume
#

abba

boreal ravine
#

Stop shitposting

torpid dew
#

why does this message not send to the channel

@client.command()
async def note(ctx, message=None):
  await ctx.send('What place are you in?')
  message = await client.wait_for("message")

  await ctx.send("What topic is this note for.")

  msg = await client.wait_for("message")
  
  if message.lower() == 'place1' and msg.lower() == 'social':
    channel = client.get_channel(channelid)
    await channel.send(message)
  else:
    pass
brave vessel
torpid dew
torpid dew
brave vessel
#

What’s the error?

torpid dew
#

nothing, just doesnt send to the channel

pliant gulch
#

As the wait_for here returns a Message

#

You want to call lower on the content attribute of the message

brave vessel
#

^ message.content.lower() and msg.content.lower() respectively should work

torpid dew
# brave vessel ^ `message.content.lower()` and `msg.content.lower()` respectively should work

<Message id={myidiwanttokeepprivate} channel=<TextChannel id=privateid name='bot-testing' position=6 nsfw=False news=False category_id=None> type=<MessageType.default: 0> author=<Member id=723041209098174554 name='Nutshell' discriminator='1239' bot=False nick='nutshell' guild=<Guild id=privateid name='servername' shard_id=None chunked=False member_count=154>> flags=<MessageFlags value=0>>

#

it gives this for some reason in the channel

brave vessel
#

Since you’re sending the message instead of the message.content

#

To access the content within the Message object it’d be [variable you set the message to].content

torpid dew
#

ok

torpid dew
brave vessel
#

Instead of await ctx.send(message) you’ll wanna do await ctx.send(message.content)

#

since message is an instance of discord.Message, so to get the actual content of the message you do message.content

boreal ravine
unkempt canyonBOT
torpid dew
# boreal ravine !d discord.Message.content
@client.command()
async def note(ctx, message=None):
  await ctx.send('What topic is it?')
  message = await client.wait_for("message")

  await ctx.send("What place is this note for.")

  msg = await client.wait_for("message")
  
  if message.content.lower() == 'test' and msg.content.lower() == 'wow':
    channel = client.get_channel(mychannel_idi_keep_private)
    await channel.message.content.send(message)
  else:
    pass
fading harness
#

hi

#

do anyone know how to make dpy code fast

boreal ravine
#

learn how to differentiate classes and attributes

boreal ravine
torpid dew
boreal ravine
#

your code was right earlier

#

but you sent the message object

fading harness
boreal ravine
fading harness
boreal ravine
#

can you give me a reason?

#

I dont quite understand what you mean

fading harness
#

i feel the code so slow

boreal ravine
#

How?

#

Show me your command/code

#

there might be something blocking it and making it slow

gilded crystal
fading harness
fading harness
fading harness
boreal ravine
boreal ravine
gilded crystal
#

Thank you guys

boreal ravine
#

what are you using then