#discord-bots

1 messages · Page 563 of 1

slate swan
#

is the file in the same folder as the main.py file?

#

no ig

#

you need to enter the path there , so it would bepy bot.load_extension('commands.somecommands')

visual island
#

it prints the function name as you can see before, _run_event is a task where dpy dispatches events, etc

supple jacinth
#

OMG TYSM

#

😄

leaden jasper
supple jacinth
#

ok so how can i make it loop through the files and load them?

slate swan
#

commands must be a list ( called array in js) with all the cog paths

supple jacinth
#

uhh

#

i know how to do it in js not py

slate swan
faint orchid
#

Did not help. It gives an error like this:

Traceback (most recent call last):
  File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Дмитрий\AppData\Local\Programs\Python\Python35-32\Scripts\pip.exe\__main__.py", line 5, in <module>
  File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\site-packages\pip\_internal\cli\main.py", line 57
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax
supple jacinth
boreal ravine
#

you need to install it first

upbeat otter
supple jacinth
#

like example

commands
  |help.py
  |ping.py

then it will loop through the files in commands so 2 files and load them

upbeat otter
#

or wait

supple jacinth
#

i dont want to put them in an array

#

list*

jovial osprey
#

hi i want to make it when an user joins it gets a role but its not working. do you know why ?

@bot.event 
async def on_member_join(member):
 role = get(member.guild.roles, id="902559208422137897")
 await member.add_roles(role)
boreal ravine
visual island
jovial osprey
boreal ravine
slate swan
jovial osprey
# boreal ravine show me what u did
@bot.event
async def on_member_join(member):
  role = discord.utils.get(member.server.roles, id=902559208422137897)
  await bot.add_roles(member, role)
slate swan
#
for commands in os.getenv('commands'):
 #loading stuff```
boreal ravine
# supple jacinth how can i do that
for filename in os.listdir("./folder"):
    if filename.endswith(".py"):
        bot.load_extension(f"folder.{filename[:-3]}")
``` literally what everyone uses
boreal ravine
#

just member.add_roles(role)

supple jacinth
#

there we go

velvet tinsel
faint orchid
velvet tinsel
#

halp me it's been going on for 2 days

velvet tinsel
#

how to fix

jovial osprey
boreal ravine
#

wait @jovial osprey does your bot have member intents

visual island
boreal ravine
#

ah

#

good thinking

jovial osprey
velvet tinsel
#

oops thamk

boreal ravine
visual island
#

wait, message content intents is already a thing?

#

just realized that 🙄

jovial osprey
boreal ravine
#

hm

visual island
#

have you set the intents in your code?

jovial osprey
#

what intents

visual island
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

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

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

visual island
#

the one in the codeblock

jovial osprey
#

oh

#

wait a second

velvet tinsel
#

hello?

#

anyone

#

?

#

heloooooo

upbeat otter
jovial osprey
upbeat otter
velvet tinsel
leaden jasper
upbeat otter
leaden jasper
#

they are coroutines

velvet tinsel
#

he only had muted, and then lost the muted role afterwards.

leaden jasper
#

i have 2 run events

#

is this a bug

upbeat otter
velvet tinsel
upbeat otter
upbeat otter
leaden jasper
upbeat otter
leaden jasper
#

what is the difference between runner and run event

#

oh

#

i think _run_event is a cog listener

#

cus i have 2 of those

visual island
velvet tinsel
leaden jasper
upbeat otter
leaden jasper
#

well how do i get_task a listener really

supple jacinth
#

how can i color code an embed?

#

like i dont get the color code stuff

#

i know hex but that doesnt work

boreal ravine
#

Can u show me what you did?

supple jacinth
#

you sure?

boreal ravine
#

yes

leaden jasper
velvet tinsel
# upbeat otter idk ;-;

ok, let me re-phrase. I'll use pseudo

@client.event
async def on_message(message):
  if spam_count > 5:
  mute(message.author)
  asyncio.sleep(10)
  unmute(message.author)

can you turn that into python? (or how)

supple jacinth
#

it doesnt work

upbeat otter
upbeat otter
velvet tinsel
boreal ravine
# supple jacinth ;-;
  1. Its supposed to be an integer.
  2. Remove the hash from the code and replace it with 0x (should be 0xDC143C)
supple jacinth
#

ok

supple jacinth
#

yay ty

leaden jasper
leaden jasper
velvet tinsel
#

I changed it to banning them then unbanning them, but I think they would be angry at me for doing that

upbeat otter
#

@velvet tinsel its because discord.utils.get() is sending None as the response

boreal ravine
#

also why 2 variables just use one

boreal ravine
velvet tinsel
visual island
boreal ravine
boreal ravine
upbeat otter
velvet tinsel
boreal ravine
leaden jasper
upbeat otter
#

My english is breaking 🥲

leaden jasper
#

after unloading the on_message one, one of the 4 tasks dissapeared

#

but unloading on_command_error didnt change anything

visual island
#

yea, i think _run_event should only be called once (at bot.start)

visual island
leaden jasper
upbeat otter
#
(embed) Go to youtube

and youtube should be clickable and should redirect to https://www.youtube.com
How do I do this?

visual island
upbeat otter
velvet tinsel
#

I fixed it, but it's sstill not muting

visual island
velvet tinsel
#

I have a server for it, do you want me to send an invite?

supple jacinth
#

yay my bot now runs 24/7 🙂

velvet tinsel
#

helop

#

my bot still won't mute

upbeat otter
visual island
upbeat otter
velvet tinsel
#

what

upbeat otter
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

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

how to i mention the author of the command?

maiden fable
random sleet
velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            role = discord.utils.get(message.author.roles, name='Muted')
            await discord.Member.add_roles(message.author, role)
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)
            await message.author.remove_roles(role)

now it's returning with

AttributeError: 'NoneType' object has no attribute 'id'

why doesn't anybody know this 😢 stack overflow hates me as well, plus the community is toxic (like, very very toxic)

slate swan
#

hello guys tell me how to auto-delete a message after a certain amount of time

random sleet
#

i get this error

velvet tinsel
#

pls help me

#

I'm legit on my knees

velvet tinsel
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "[_________]", line 343, in _run_event
    await coro(*args, **kwargs)
  File "[___________]", line 42, in on_message
    await discord.Member.add_roles(message.author, role)
  File "[______________________]", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
hasty iron
#

role is None

velvet tinsel
#

so how do I fix

hasty iron
#

discord.utils.get(message.author.roles, name='Muted') this returned None

#

i think you mean message.guild.roles

velvet tinsel
#

how do I fix, logic didn't work

#

pls

#

😫

hasty iron
#

what?

#

i told you what i think

velvet tinsel
#

ok

#

sorry I didn't see that 😛

#

wait why is he smiling

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\[___]\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\[________]\PycharmProjects\Dave\main.py", line 41, in on_message
    role = message.guild.roles(message.author.roles, name='Muted')
TypeError: 'list' object is not callable
#

😫 python hates me

maiden fable
velvet tinsel
maiden fable
velvet tinsel
#

you're contradicting blanket, and plus if I do that it would have an error

hasty iron
#

?

#

you should probably learn more python

maiden fable
#

Nvm, why did I even say that 🤦

velvet tinsel
#

who me

#

I am trying to

hasty iron
maiden fable
velvet tinsel
#

nope

boreal ravine
#

can I just spoonfeed

velvet tinsel
#

yes please

hasty iron
maiden fable
velvet tinsel
#

I don't care anymore

hasty iron
#

no don't

#

they dont even know python

velvet tinsel
#

bruh, I've tried for 2 days

hasty iron
#

learn more python

boreal ravine
hasty iron
#

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

velvet tinsel
#

I have lessons for python, what do you think I'm doing

hasty iron
hasty iron
velvet tinsel
#

I did pass in message.guild.roles

velvet tinsel
unkempt canyonBOT
#

Hey @jovial osprey!

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

boreal ravine
velvet tinsel
#

stack overflow doesn't let me ask questions for a week

#

😦

hasty iron
hasty iron
velvet tinsel
#

Is nobody gonna help me

vagrant brook
#

I'm sure you don't have enough OOP knowledge so just go back and learn some python ig

boreal ravine
velvet tinsel
#

bruh

hasty iron
#

discord.py isn't something a beginner should do in a learning phase

boreal ravine
velvet tinsel
hasty iron
boreal ravine
#

which error

hasty iron
#

in their code they did discord.Member.add_roles(message.author, ...)

vagrant brook
#

Well he tried discord.Member.add_roles

hasty iron
#

which clearly shows lack of knowledge

vagrant brook
#

Which shows that he doesn't know basic OOP

boreal ravine
velvet tinsel
# hasty iron it does
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\[___]\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\[________]\PycharmProjects\Dave\main.py", line 41, in on_message
    role = message.guild.roles(message.author.roles, name='Muted')
TypeError: 'list' object is not callable
late dock
#

How to change embed colour?

velvet tinsel
#

I went through an entire book of python

hasty iron
boreal ravine
jovial osprey
#

i have another problem, i want to make it that when i press a button i will get a role but it doesnt works it says: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'

heres the code ```py
@bot.command()
@commands.has_role("「💻」 Bot Developer")
async def skin(ctx):
embed = discord.Embed(
title = "Vytvorenie skinu",
description = "Toto je popisok.",
colour = discord.Colour(0x80ff80)
)

embed.set_footer(text="bot made by samuelll hehe")
embed.add_field(name="Meno poľa", value="Niečo 1", inline=False)
await ctx.send(embed=embed)
await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Len testujem buttny", components=[Button(style=3, label="Default Button", custom_id="button")])

res = await bot.wait_for("button_click")
if res.channel == ctx.channel:
    member = res.guild.get_member(res.user.id)
    await member.add_roles(902869731223150642)
    await res.respond(
        type=InteractionType.ChannelMessageWithSource,
        content=f"{res.component.label} has been clicked!"
velvet tinsel
slate swan
hasty iron
velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            role = message.guild.roles(message.author.roles, name='Muted')
            await discord.Member.add_roles(message.author, role)
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)
            await message.author.remove_roles(role)
vagrant brook
#

right

boreal ravine
#

its all right

hasty iron
#

right, exaclty what i said

velvet tinsel
#

I removed everything that caused an error, apart from message.guild.roles

hasty iron
#

yeah, i told you to call message.guild.roles

boreal ravine
#

@velvet tinsel i dont see anything wrong here though

velvet tinsel
#

no I didn't update that

boreal ravine
#

anything wrong

late dock
slate swan
#

do a hex number

hasty iron
#

0x

slate swan
#

color=0xhex

boreal ravine
velvet tinsel
#

wait I'm trying something

late dock
#

Ohk

slate swan
#

color=0x009900 I guess

pearl idol
#

pls bal

late dock
#

It works now thanks

velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            role = discord.utils.get(message.guild.roles, name='Muted')
            await discord.Member.add_roles(message.author, role)
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)
            await message.author.remove_roles(role)

would this work?

pearl idol
#

bsdk bal

slate swan
velvet tinsel
boreal ravine
pearl idol
velvet tinsel
#

I did

slate swan
pearl idol
#

No dank here

reef shell
#

bro wtf

#

this ain't the server you're looking for

velvet tinsel
#

but keeping discord.utils.get?

boreal ravine
#

I literally dont see any errors

velvet tinsel
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\\PycharmProjects\Dave\main.py", line 42, in on_message
    await discord.Member.add_roles(message.author, role)
  File "C:\Users\\PycharmProjects\Dave\venv\lib\site-packages\discord\member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
boreal ravine
#

in that code whatsoever

late dock
#

It is possible to use Json on Python?

velvet tinsel
#

No, I wanted it to mute the person. What I'm saying is that it doesn't.

boreal ravine
hasty iron
velvet tinsel
boreal ravine
#
        mutedRole = discord.utils.get(guild.roles, name="Muted")
hasty iron
#

what code are we even talking about

#

this is too confusing

boreal ravine
velvet tinsel
#

that one is wrong

boreal ravine
#

it was already correct

#

it isnt

#

which part of the link i sent

velvet tinsel
#

but I had to remove the second mutedRole variable

boreal ravine
#

was wrong?

boreal ravine
rare saddle
#

How to make a condition that if A person in a particular channel has sent a message, then the bot will forward this message, and then delete the author's message

vagrant brook
#

What have you tried yet

velvet tinsel
#

No error, but it doesn't mute

boreal ravine
pearl idol
#

Guys I have code

boreal ravine
#

bruh

velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            mutedRole = discord.utils.get(guild.roles, name="Muted")

            if not mutedRole:
                mutedRole = await guild.create_role(name="Muted")
                for channel in guild.channels:
                    await channel.set_permissions(mutedRole, speak=False, send_messages=False,
                                                  read_message_history=True, read_messages=False)
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)

            await message.author.remove_roles(mutedRole)
vagrant brook
#

You literally did remove_roles

boreal ravine
#

too many things

vagrant brook
#

How can it mute if you remove role

velvet tinsel
#

I think it was the wrong code I sent

boreal ravine
#

!d discord.Member.add_roles just use this

unkempt canyonBOT
#

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

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

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

Apparently I don't see any add_roles

pearl idol
boreal ravine
boreal ravine
pearl idol
#

Can I send the replit link or the code itself

velvet tinsel
#

It's the same result

boreal ravine
late dock
#

What does invoke_with_command do?

boreal ravine
velvet tinsel
velvet tinsel
boreal ravine
pearl idol
#

How do I paste a big code

#

It is not allowing

slate swan
# late dock What does `invoke_with_command` do?

invoke_without_command when set to True will try to invoke the subcommand first, if no subcommand found, invoke the group command, when set to False, it will invoke the group command, along with subcommand when it found one

boreal ravine
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.

velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            mutedRole = discord.utils.get(guild.roles, name="Muted")

            if not mutedRole:
                mutedRole = await guild.create_role(name="Muted")
                for channel in guild.channels:
                    await channel.set_permissions(mutedRole, speak=False, send_messages=False,
                                                  read_message_history=True, read_messages=False)
            await message.author.add_roles(mutedRole, reason="spam")
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)

            await message.author.remove_roles(mutedRole)
velvet tinsel
#

nope

#

it only doesn't mute

#

is it something to do with asyncio??

boreal ravine
#

try debugging the command

boreal ravine
velvet tinsel
#

I debugged it, it still doesn't mute me

pearl idol
#

Not working guys

velvet tinsel
boreal ravine
unkempt canyonBOT
#

Pasting large amounts of code

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

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

tawdry perch
velvet tinsel
rare saddle
#

How to make sure that if a message is sent to the chat, then the bot sends it to another chat, and the first message is deleted?

tawdry perch
#

So do you get the role?

velvet tinsel
#

yes

tawdry perch
#

Then it's about role settings

pearl idol
#

Like 118 lines

velvet tinsel
tawdry perch
#

!paste it here

unkempt canyonBOT
#

Pasting large amounts of code

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

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

velvet tinsel
slate swan
#

With python i can do a custom help command like:

tawdry perch
slate swan
#

?

velvet tinsel
velvet tinsel
rare saddle
reef shell
unkempt canyonBOT
#

Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

tawdry perch
# velvet tinsel yes

Do in channel they can only read message history/view channel. Do same to role perms settings

reef shell
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.

This is usually represented as a drop down menu.

In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Select.values "discord.ui.Select.values").

New in version 2.0.
slate swan
# rare saddle

that's the discord.Message repr, if you want to get the content just, message.content, and send that instead

pearl idol
pearl idol
#

Good to go

pearl idol
velvet tinsel
#

well, it's doing nothing

#

still

boreal ravine
pearl idol
#

No

velvet tinsel
#

now my entire message history between the bot and me is stop spamming! stop spamming! stop spamming!

boreal ravine
pearl idol
#

Just a noob thing

pearl idol
#

I had no idea more than that

#

Can't we run the code directly in hastebin

pearl idol
boreal ravine
#

i do

#

its just that its not related

velvet tinsel
#

bruh

boreal ravine
velvet tinsel
#

my bot is unresponsive

#

🧠 🔫

hasty iron
velvet tinsel
#

thats basically my bot rn

boreal ravine
#

use .listen()

#

if ur using an on message

#

and the bot doesn't respond

velvet tinsel
#

OHHHH

boreal ravine
#

ok no need to share that.

velvet tinsel
#

nothing happened

#

apart from the bot saying Stop spamming!

#

what do I do

#

should I give up on the muting thing

slate swan
#

Success isnt always easy

rare saddle
#

How to make it so that if the message is more than 1024 characters then not to forward it?

boreal ravine
boreal ravine
#

message.content

rare saddle
#

yea

#

thanks

velvet tinsel
#

my bot is unresponsive

slate swan
rare saddle
#

Why is that?

boreal ravine
velvet tinsel
#

wahh

#

I'll stop the muting thing

rain ridge
#

how do u use author's pfp in embed

rare saddle
rain ridge
slate swan
#

embed=emb

boreal ravine
unkempt canyonBOT
#

property author: _EmbedAuthorProxy```
Returns an `EmbedProxy` denoting the author contents.

See [`set_author()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.set_author "discord.Embed.set_author") for possible values you can access.

If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
slate swan
boreal ravine
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**.
boreal ravine
#

no spoonfeed

slate swan
#

k

rare saddle
#

ohhhh, yea thanks @slate swan@boreal ravine

boreal ravine
#

ok

slate swan
#

what'd would spoon feed mean?

#

like not giving them solution rather hints?

boreal ravine
#

yes

slate swan
boreal ravine
#

yes

velvet tinsel
boreal ravine
#

it is

slate swan
slate swan
velvet tinsel
#

I did

#

I tried my best

#

but it turned out bad 😦

slate swan
velvet tinsel
#

well

#

I did and it didn't work

slate swan
#

Try way harder than ever before

slate swan
velvet tinsel
#

ok

slate swan
#

And hard work

rain ridge
#

ah i got the my answer

night seal
#

Hi I have a doubt

#

Pls anyone help

rain ridge
#

what is it?

night seal
#

I am like stuck
I want to make a feature for my discord bot which tells you the server info
I dont know how to do it

rain ridge
#

like no-of members / channel etc?

night seal
#

yes

#

this is my friends bot

leaden jasper
night seal
#

i want like this

leaden jasper
night seal
supple jacinth
covert igloo
#

@leaden jasper heroku 50peek

night seal
#

@rain ridge pls help

velvet tinsel
#
# doing some detecting...
@client.event
async def on_message(message):
    guild = message.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            mutedRole = discord.utils.get(guild.roles, name="Muted")

            if not mutedRole:
                mutedRole = await guild.create_role(name="Muted")
                for channel in guild.channels:
                    await channel.set_permissions(mutedRole, speak=False, send_messages=False,
                                                  read_message_history=True, read_messages=False)
            await message.author.add_roles(mutedRole, reason="spam")
            await message.author.send("Stop spamming!")
            await asyncio.sleep(10)

            await message.author.remove_roles(mutedRole)
leaden jasper
velvet tinsel
#

and there is no error, it just doesn't do anything

covert igloo
slate swan
night seal
#

@rain ridge

supple jacinth
#

its not really plus its not reliable

night seal
#

just tell if am right

covert igloo
slate swan
slate swan
supple jacinth
#

uptimerobot is wdym

slate swan
slate swan
leaden jasper
slate swan
#

Can't compare to an actual payed vps tho

covert igloo
#

I've never used uptime before but for being free heroku is the best for me

velvet tinsel
slate swan
night seal
#

@rain ridge

#

can you dm me?

slate swan
#

Why are so many people using .txt files instead of json 😭

slate swan
#

Or just a normal dict, that works too 💀

leaden jasper
supple jacinth
slate swan
velvet tinsel
night seal
#

can anyone help me

leaden jasper
slate swan
velvet tinsel
#

ok

supple jacinth
#

raspberry pi 4 is best, just make sure to get a cooling case as it gets really hot

slate swan
velvet tinsel
#

ok

leaden jasper
magic pond
#
@client.command()
async def create_channel(ctx,msg1):
        guild = client.get_guild(guild_id)
        channel = await guild.create_text_channel({msg1})
#

whts wrong here?

night seal
#

yes

slate swan
craggy cloak
#

@client.has_any_role(886987124623151176) @commands.cooldown(1, 60, commands.BucketType.user) @client.command()

supple jacinth
night seal
slate swan
leaden jasper
#

!d discord.Guild.member_count

unkempt canyonBOT
#

property member_count: int```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
leaden jasper
magic pond
night seal
#

i cant

magic pond
#

?

night seal
#

thats why i cam here

slate swan
slate swan
night seal
#

yes

night seal
echo patrol
#

Hi guys! Does any1 have a good intro to discord bots python resource online?

night seal
#

like where do i start

echo patrol
#

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

leaden jasper
late dock
#

FileNotFoundError: [Errno 2] No such file or directory: 'BlockInfo.json'
What happen here?

leaden jasper
late dock
#

But that on same directory as python file

slate swan
leaden jasper
#

line 38 downwards

#

u dont need to copy everything just pick what u need

slate swan
slate swan
#

Yeah but you have the bills

supple jacinth
slate swan
#

Both electricity and internet bills

supple jacinth
#

i also do alot of things on it

supple jacinth
night seal
#

wait

slate swan
#

Like ovh for exmaple, you can pay 4 bucks monthly for a really good VPS

slate swan
slate swan
#

Also more reliable because there's more chances of your electricity going down rather than the vps's providers

craggy cloak
#
@commands.has_any_role(886987124623151176)

How can I create an error message for the users who do not have this role?

reef shell
slate swan
reef shell
#

Not actually selfbot or userbot ig

slate swan
slate swan
# slate swan Yeah

It depends if it has like a heavyweight package or a premium one stuff like that but if you have a rpi it can be a server just for you that you dont need to pay each month or worry about your money in your paypal or stuff like that

slate swan
#

Both good but i prefer a rpi

#

There's electricity and internet bills that the rpi increases

#

can someone help me with how i would check a users role then display it inside of an embed? cant figure it out=

slate swan
#

Yeah

slate swan
unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
slate swan
#

Idk i prefer a rpi cuz its fisical and other stuff

#

It may look cool and fun but a vps is more practical, reliable and cheap

slate swan
slate swan
#

It's alr

rapid whale
#
@commands.command(aliases = ['q'])
    async def quote(self , ctx , message: discord.Message):
        a = message.jump_url
        b = message.content
        c = message.channel.name
        d = message.created_at
        embed = discord.Embed(timestamp = ctx.message.created_at, color = message.author.colour , description = "{}".format(b))
        embed.set_author(name = str(message.author) , icon_url = message.author.avatar.url)
        embed.add_field(name = "Link" , value = '[Springe zur Nachricht]({})'.format(a) , inline = True)
        embed.add_field(name = "Geschrieben am:", value = "**<t:{}:{}>**".format(int(d.timestamp()), "F"), inline = True)
        embed.set_footer(text = "#{}".format(c))
        return await ctx.reply(embed = embed)

If I try to get the message content of an embed it only respond with 'Springe zur Nachricht' and 'Geschrieben am' and not with the content in general. How could I do that?

slate swan
rare saddle
#

And where you can see all time formats by type - And where you can see all time formats by type - %x | %H:%M

velvet tinsel
#

how do you tell if a dictionary contains something?

hasty iron
#

if key in dict

night seal
#

guys whats wrong here

slate swan
#

Do yourself a favor, and use commands

#

It's gonna make your life a ton easier ok_handbutflipped

#

got a question about checking what role a user has then printing it in an embed in #help-cookie if anyone wants to swing by

#

dose anyone know the announce command code

night seal
#

what do i change @slate swan

#

where is the error

boreal ravine
versed shell
#

Hey is anyone able to help me with a question?

boreal ravine
#

?

versed shell
#

I have a command that splits the message content , however if someone doesnt type the command and another word like (!command word) it crashes. How would I get it to ignore the command if it doesnt have the second word

#

sorry if that was worded poorly lol

boreal ravine
#

hm

slate swan
boreal ravine
boreal ravine
#

in your code

slate swan
#

i don't have the link to where it's showcased how to use commands but it's in the docs if you look for it

spiral frigate
#

Who knows where my mistake is

    @commands.command(name= "мемчик")
    async def mem(self, ctx):

        des = random.choice(["Я пришёл разнести вас по личным причинам.", "Неправильный не я… Неправильный весь этот мир.", "Я просто подвигами маюсь.", "Выбор – это всегда только компромисс или эгоистичный ход в своих интересах. Только так.", "В конце концов, весь мир вращается вокруг меня!", "Терпеть не могу пороховой огонь, он понятия не имеет о хороших манерах.", "Если вам нечего делать, то не надо делать это здесь!", "Дураки любят высокие места.", "Сейчас мы покажем, на что способны… БЕЖИМ!!!", "Мы дойдем до самого конца! А потом еще куда-нибудь…", "Враньё – это путь к популярности."])

        embed = discord.Embed(title="Цитата:" , description=f"{des}")

        async with aiohttp.ClientSession() as cs:
            async with cs.get('https://www.reddit.com/r/animememes/random.json') as r:
                res = await r.json()

                embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
                await ctx.send(embed=embed)
cloud dawn
#

That is because slash is meant to work with a bot not a client.

spiral frigate
#

yes this is api reddit

spiral frigate
#

I'm telling you it doesn't affect this command

#

I'm importing

slate swan
#

Then don’t ask for help if you can’t show

spiral frigate
#
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
import aiohttp


class Info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
#

The rest of the code is commands that work fine

late dock
#

How to take JSON Value into embed?

Example
"name": "This is Title"
I want the value of name is imported to Embed Title

slate swan
#

value_for_name_key = thejson['name']

spiral frigate
#

error

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 211, in mem
    embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
TypeError: list indices must be integers or slices, not str

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\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: TypeError: list indices must be integers or slices, not str
#

good thanks

#

And where to find it user_agent

#

@slate swan

#

And how to get it out then

#
reddit = praw.Reddit(client_id='CLIENT_ID HERE',
                     client_secret='CLIENT_SECRET HERE',
                     user_agent='USER_AGENT HERE')
#

Here you threw me the first 2 I led

acoustic ermine
#

How can I get another bots embed and get my bot to relay that embed

#

Would I use get_message?

slate swan
#

fetch_message

#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
slate swan
#

with this Message object, you can do
yourMessageObjectName.embeds[0]

#

can someone explain why


    @commands.command(name="profile2")
    async def _profile(self,ctx,member: discord.Member=None):
        if not member:
            member = ctx.author
        pfp = member.avatar_url
        membermention = ctx.author.mention
        ages = ['15', '16']
        memberroles = [role.name for role in member.guild.roles]
        age = [i for i in ages if i in memberroles] # contains all "age" roles
        if not age: # if they dont have any age roles
          text = 'No role'
        elif age[0] == '15':
          text = '15 years underage'
        elif age[0] == '16':
          text = '16'
        embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
        embed.set_thumbnail(url=(pfp))
        embed.add_field(name="Verification", value="Verified", inline=True)
        embed.add_field(name="Age", value=text, inline=True)
        embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
        with open('blacklist.json', 'r') as file:
            file = json.load(file)
        if str(member.id) in file:
            embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
        await ctx.send(embed=embed) ```

doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
#

it always just displays "15 years underage"

velvet tinsel
#

is there any way to create an economy bot that stores value for a person, or does that require dicts and databases?

#

I think it requires dicts and databases

slate swan
#

ofc it does

#

only one database

spiral frigate
#

writes when sending a meme

It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
velvet tinsel
#

do I store it in a .txt file?

slate swan
spiral frigate
#

code

    async def meme(self, ctx):

        reddit = praw.Reddit(
        client_id='A5HNPvyhKCAj5l64h8R9RQ',
        client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
        user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
        )

        memes_submissions = reddit.subreddit('memes').hot()
        post_to_pick = random.randint(1, 10)
        for i in range(0, post_to_pick):
            submission = next(x for x in memes_submissions if not x.stickied)

        await ctx.send(submission.url)
velvet tinsel
velvet tinsel
slate swan
#

wdym aswell

#

I said no txt

velvet tinsel
slate swan
#

yes, I know what a dict is

velvet tinsel
#

ok, so only databases work

slate swan
#

I'm saying it's nothing powerful nor easy to use

velvet tinsel
#

right?

velvet tinsel
slate swan
slate swan
velvet tinsel
#

or I make a new python file and never run it but store everything in it

slate swan
velvet tinsel
slate swan
slate swan
slate swan
velvet tinsel
#

but it would crash my computer

slate swan
#

that's the exact opposite of what we suggest

velvet tinsel
#

storing that many data on my computer would send it alight

slate swan
#

json is made for static data

slate swan
velvet tinsel
#

or would it not?

slate swan
slate swan
slate swan
slate swan
velvet tinsel
slate swan
#

I know

#

I'm just agreeing

#

but not to the json idea

slate swan
velvet tinsel
slate swan
#

well ,if they were forced to pick between txt and json, i'd say go with json

velvet tinsel
slate swan
#

oh

slate swan
velvet tinsel
#

And a small question, can you create buttons for games using discord.py?

slate swan
#

even companies wouldn't force anybody to use a json as a db

slate swan
#

there's no case where you can use txt and json but not sqlite , its an internal python library

velvet tinsel
slate swan
velvet tinsel
#

what do you mean, beta version?

sick birch
#

it's called beta but imo it's pretty stable

slate swan
#

it aint available on pypi yet so pip install discord.py wont install it

velvet tinsel
#

oh wait nevermind

slate swan
#

you need to use git

velvet tinsel
#

I found it

#

wait, I thought they stopped production on discord.py

slate swan
#

yes

spiral frigate
#

I don't understand how to install asyncpraw in my code


        reddit = asyncpraw.Reddit(
        client_id='A5HNPvyhKCAj5l64h8R9RQ',
        client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
        user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
        )

        memes_submissions = reddit.subreddit('memes').hot()
        post_to_pick = random.randint(1, 10)
        for i in range(0, post_to_pick):
            submission = next(x for x in memes_submissions if not x.stickied)

        await ctx.send(submission.url)
slate swan
#

they did

spiral frigate
#

I looked at the documentation and didn't understand

slate swan
#

not sure , but everything other than slash commands was already implemented

sick birch
#

you can make slash commands with d.py yourself pretty easily

#

or at listen to them

spiral frigate
sick birch
#

to get a random meme and post it

spiral frigate
#

I initially used the usual praw.
B everything worked but wrote that it was better to use asynchronous praw

verbal forge
#

Can I make a pokemon bot using python? coz in youtube everybody is showing withs javascript.

slate swan
#

except voice receiving

#

you would have to make the fork first

verbal forge
spiral frigate
#

if you use this code then writes this:
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.

        reddit = praw.Reddit(
        client_id='A5HNPvyhKCAj5l64h8R9RQ',
        client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
        user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
        )

        memes_submissions = reddit.subreddit('animememes').hot()
        post_to_pick = random.randint(1, 10)
        for i in range(0, post_to_pick):
            submission = next(x for x in memes_submissions if not x.stickied)

        await ctx.send(submission.url)
slate swan
verbal forge
tough lance
#

Wdym?

slate swan
#

can someone explain why


    @commands.command(name="profile2")
    async def _profile(self,ctx,member: discord.Member=None):
        if not member:
            member = ctx.author
        pfp = member.avatar_url
        membermention = ctx.author.mention
        ages = ['15', '16']
        memberroles = [role.name for role in member.guild.roles]
        age = [i for i in ages if i in memberroles] # contains all "age" roles
        if not age: # if they dont have any age roles
          text = 'No role'
        elif age[0] == '15':
          text = '15 years underage'
        elif age[0] == '16':
          text = '16'
        embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
        embed.set_thumbnail(url=(pfp))
        embed.add_field(name="Verification", value="Verified", inline=True)
        embed.add_field(name="Age", value=text, inline=True)
        embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
        with open('blacklist.json', 'r') as file:
            file = json.load(file)
        if str(member.id) in file:
            embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
        await ctx.send(embed=embed) ```

doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
#

it always just sends the first possible value

#

e.g 15, then if i edit 15 to a random number like 99 it'll send 16, then if i edit both to random numbers it says

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range

slate swan
#

im trying to mention a random member but the bot just mentions itself

@bot.command()
async def randommember(ctx):
    await ctx.send(f"{random.choice(ctx.guild.members).mention}")

should i do this?

for member in ctx.guild.members:
        if member == user.bot:
            #do something
sick birch
#

if you don't have guild member intents then the only thing ctx.guild.members returns is yourself

slate swan
#

Or is intents just permission to see other members

steady flume
#

guys, I created buttons (version 2 of the Danny library) and I created them in a separate file, but how do I respond to these buttons in another file?

#
  1. import this class
  2. make view
  3. and how i can respond to buttons ?
#

pls help

sick birch
#

guild, guild members, message intents, presence intents, etc...

steady flume
#
        while True:
            interaction = await self.client.wait_for("button_click")
            if interaction.custom_id == "colours":

this doesnt work

sick birch
steady flume
#

heh

#

didnt understand

sick birch
#

you have a subclass correct?

#
class MyView(discord.ui.View):
  ...

Like that?

slate swan
steady flume
#

idk heh

#

too diff questions, imma send my small work

sick birch
#

i suggest check out the examples on the github

#

/examples/views

steady flume
#
class ShopView(discord.ui.View):
    """
            This view creates shop buttons"
    """

    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Colours",
                       custom_id="colours",
                       style=ColorsConfig.colours, emoji="🎨")
    async def colours(self, button: discord.ui.Button, interaction: discord.Interaction):
        pass

i made button

sick birch
#

right

#

you're already responding to it

#

async def colours() is what's called when the button is pressed

steady flume
#
 async def server_shop(self, ctx):
        view = ShopView()
        edit_embed = discord.Embed(
            description="Select the category of products that you would like to see",
            color=0x2f3136
        )
        edit_embed.set_author(name="💳 Server Shop")
        edit_embed.set_footer(text=f"Requested by{ctx.author.name}", icon_url=ctx.author.avatar.url)
        embed = await ctx.reply(embed=edit_embed, view=view, mention_author=True)

        while True:
            interaction = await self.client.wait_for("button_click")
            if interaction.custom_id == "colours":
                embed2 = discord.Embed(
                    title="Colours:",
                    description="``1.`` <@&840311378455429122> ``800``:coin:\n``2.`` <@&840312261939560508> ``800``:coin:\n``3.`` <@&840312664911249438> ``800``:coin:\n``4.`` <@&840313421764886539> ``800``:coin:\n``3.`` <@&840312664911249438> ``800``:coin:\n``4.`` <@&840313421764886539> ``800``:coin:\n``8.`` <@&850108513514684416> ``800``:coin:"
                )
                await embed.edit(embed=embed2)

this is another file

#

how i can resons

sick birch
#

you're doing it right

#

but not the interaction part

steady flume
#

ty

steady flume
sick birch
#

to respond to interactions, put the code within the async def colours()

#

replace your pass with the callback logic

sick birch
#

no, that's the coro that's called when the button is clicked

#

so put your code that you want to run when the button is clicked inside it

#
class MyView(discord.ui.View):
  def __init__(...):
    super().__init__(...)
  
  @discord.ui.button(...)
  async def myCallback(...):
    print("User clicked a button")
#

for a more complete example, you should check out the /examples/views folder on the github page

steady flume
#

okey

#

thank you!, ill try do smth

#

but still i need respond to button in a another file

sick birch
#

you can just import the class and initialise it

steady flume
#

show example please)))))

sick birch
#

buttons.py:

class MyView(discord.ui.View):
  def __init__(...):
    super().__init__(...)
  
  @discord.ui.button(...)
  async def myCallback(...):
    print("User clicked a button")

mainbot.py:

from buttons import MyView

async def someCommand(...):
  view = MyView()
  await ctx.send(view=view)
steady flume
#

bruh, i knew that

#

i made same

sick birch
#

well that's awesome then you know how to do it

steady flume
#

but in my command i made embed

sick birch
#

90% of your code is perfect

#

you can pass in anything you want to the view class

steady flume
#

i want when we click on button - edit this embed

sick birch
#

yeah pass that into the view class

#
class MyView(discord.ui.View):
  def __init__(..., new_embed):
    super().__init__(...)
    self.new_embed = new_embed
  
  @discord.ui.button(...)
  async def myCallback(...):
    await interaction.response.edit_message(embed=self.new_embed)
#

your main file would look like so:

from buttons import MyView

async def someCommand(...):
  embed = discord.Embed(...)
  view = MyView(new_embed=embed)
  await ctx.send(view=view)
#

you get the point

steady flume
#

new_embed - where i need create it, above await interaction.response.edit_message(embed=self.new_embed) ?

cyan sundial
#

how do i download a users profile picture?

sick birch
#

it doesn't really matter where you make it

#

as long as you pass it into the view class

hasty iron
unkempt canyonBOT
#

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

Saves this asset into a file-like object.
steady flume
#

i will try rn

quasi pawn
#
@commands.command(name="Backgrounds", aliases=["bgs"])
    async def backgrounds(self, ctx):
        x = '\n'.join(str(y) for y in options.keys())
        y = '\n'.join(str(x) for x in range(len(options)))
        embed = nextcord.Embed(description=f"{}")
        embed.set_author(name=ctx.author.name + "#" + ctx.author.discriminator,
                         icon_url=ctx.author.avatar.url)
        embed.timestamp = datetime.datetime.utcnow()
        await ctx.send(embed=embed, allowed_mentions=am)

How do I do it so it display like this in the description
1 word
2 word

sick birch
slate swan
steady flume
#

@sick birch your code works! ty!, but if u dont mind - can i ask u a few questions more ??

slate swan
#

How do i delay a command? I tried
time.sleep() and it just pauses the whole scirpt im trying to pause the command only

manic wing
slate swan
#

It delays a async command?

manic wing
#

yes

#

it asynchronously stops

slate swan
#

And comes again right

manic wing
#

yes.

slate swan
#

Thank you very much

jovial osprey
#

Hi, is there a way to create a text channel just for a specific person that asked for it and noone more ?

kindred epoch
#

Use permissions to exclude everyone else out besides the author

jovial osprey
#

does anyone have a code for it ? i cant find any tutorials

tawdry perch
#

I have made one but it's closed source

kindred epoch
#

Code it yourself maybe?

#

Noone is going to spoonfeed

jovial osprey
#

i dont know how ?

#

never done it ?

kindred epoch
#

So?

tawdry perch
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
jovial osprey
#

thanks for atleast some info

kindred epoch
#

Hm

tawdry perch
#

Ahh ye overwrites as well

#

!d discord.TextChannel.overwrites

#

@jovial osprey

#

I guess it's this one

jovial osprey
#

thanks

oak falcon
#

hi guys, I am working on some bots and noticed there are threads since some time, did anyone try those already?

#

discord.py does not support it directly I guess, it is on feature branch

#

I think it will come with realease 2.0

#

I am wondering what is the best way to update my library with this feature branch, do I simply checkout the branch and merge and then switch lib files?

#
Discord Developer Portal

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

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

#

this is a pert of TextChannel?

slate swan
#

Why am I recieving this error? I swear this is correct

    @commands.command(aliases=["bal"])
    async def balance(self,ctx,  user: discord.Member = None):

        if user == None:
        
            bal_em = discord.Embed(title = f"{user.mention}'s Balance", description = f" {user.name} has a balance of",colour=0xFFA500)
            await ctx.send(embed=bal_em)

        else:

            bal_em = discord.Embed(title = f"{ctx.author.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
            await ctx.send(embed=bal_em)
bal_em = discord.Embed(title = f"{user.mention}'s Balance", description = f" {user.name} has a balance of",colour=0xFFA500)

AttributeError: 'NoneType' object has no attribute 'mention'

oak falcon
#

if user == None:

#

user.mention

past ermine
#

Hi so I have gthis cmd

    cur.execute(f'''INSERT INTO banlist (user_id) VALUES ({user}) (reason) VALUES ({reason}) (moderator) VALUES ({ctx.message.author})''')    
``` or more line but it **always** gives me a syntax error
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 107, in ban
    cur.execute(f'''INSERT INTO banlist (user_id) VALUES ({user}) (reason) VALUES ({reason}) (moderator) VALUES ({ctx.message.author})''')
sqlite3.OperationalError: near "(": syntax error
oak falcon
#

this is why

slate swan
#

replace == with !=

#

you messed up the logic my guy

slate swan
oak falcon
#

try like this:

#

if user:

slate swan
#

...

#

How can i make a cooldown on one of my commands?

oak falcon
#

what do you mean by cooldown?

slate swan
oak falcon
#

you need counter

#

I will go smoke now, I come back to you

slate swan
slate swan
tawdry perch
#

And I would recommend aiosqlite instead of SQLite3 module.

past ermine
slate swan
#

client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
    client.counter += 0.02
    client.this_dict[ctx.author.id] = client.counter
    await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
    await asyncio.sleep(60*(30))
    client.counter = 0

@client.command()
async def checkbac(ctx, *, arg : discord.Member):
    await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[ctx.author.id]}')
    if ctx.author.id not in client.dict:
        return await ctx.send('0.00')
#

huhhhhhhhhhh

    bal_em = discord.Embed(title = f"{user.name}'s Balance", description = f" {user.mention} has a balance of",colour=0xFFA500)
AttributeError: 'NoneType' object has no attribute 'name'
#

This is working
but for some reason, everyone has the same BAC level
prob messed up dict

slate swan
oak falcon
#

Did anyone use discord.Threads?

slate swan
#

you can use disnake, it's a fork of dpy so it has dpy's 2.0 syntax, and it's by far the most promising and most stable with the latest features compared to any other fork

oak falcon
#

It is a new feature

kindred epoch
slate swan
#

nvm brain fart

#

i created a global dict

kindred epoch
#

Ok, do you think that's a good idea?

slate swan
#

wel to store the value yea

kindred epoch
#

Have you heard of a database?

slate swan
#

database stores it forever thi

#

i want the avlues to reset after 30 mins

#

so wouldnt dict be the best option?

kindred epoch
#

No

#

You can delete it after 30 mins

slate swan
#

docs pls

kindred epoch
#

Use tasks.loop to delete it after every 30 mins, I would suggest using postgres as ur db

slate swan
#

ok ill check it out thanks

#

but just wanted to know: what exactly is the error in the code?

#

There is no error, its working fine, also showing the BAC, but the bac for everyone is the same

#

im guessing it has to do with ID

kindred epoch
#

Idk

#

Show how you're adding it

slate swan
#

What database should i use?

hasty iron
#

mongodb for nosql and postgresql for sql

slate swan
#

client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
    client.counter += 0.02
    client.this_dict[ctx.author.id] = client.counter
    await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
    await asyncio.sleep(60*(30))
    client.counter = 0

@client.command()
async def checkbac(ctx, *, arg : discord.Member):
    await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[ctx.author.id]}')
    if ctx.author.id not in client.dict:
        return await ctx.send('0.00')
#

@kindred epoch

slim whale
#

ideas for commands??

slim whale
slate swan
#

if i do !drink it goes up by 0.02, i do !drink again now its 0.04

kindred epoch
slim whale
#

multi functional

slate swan
#

i do !checkbac @slate swan it says i have BAC of 0.04

slim whale
#

so i dont care about the command xd

slate swan
#

but everyone has the same BAC

#

like everyone in the server has the same BAC

kindred epoch
slate swan
#

no

#

thats the probllem

#

even if somoene has never done !drink, they'd still have the same BAC as me

#

everyone in the server has the same counter

kindred epoch
#

no idea tbh

slate swan
#

ok

primal fox
slate swan
#

i did use a dict

#

@primal fox

primal fox
#

oh I see

slate swan
#

client.this_dict = {}
client.this_dict[ctx.author.id] = client.counter

would basically end up with {'myID' : 0.02}

primal fox
#

oh I see why

slate swan
#

yep but everyone has the same counter

#

even if someone has never done that drink cimmand

primal fox
#

you are referencing ctx.author.id every time, not the user you are mentioning's ID

kindred epoch
#

holy

slate swan
#

i knew i was messing up there

#

how about this:

kindred epoch
primal fox
#
await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[arg.id]}')
kindred epoch
#

^

primal fox
#

however

kindred epoch
#

even i mess up like that

primal fox
#

you should put if arg.id not in client.this_dict: return await ctx.send('0.00')
first

kindred epoch
#

^

primal fox
#

yeah, forgot lol

slate swan
#

OHH WAit i understand now

primal fox
#

arg.mention is a string

slate swan
#

it was giving the BAC of the person running the command

primal fox
#

it has no ID

slate swan
#

oh wait i got it il fix it now

primal fox
#

you could clean this up a lot more. you don't need to sleep in your first command

#

ah, I guess you're going for some effect of it returning to 0 like real life? lol

slate swan
#

after 30 mins it resets and goes back to 0

coral vessel
#

How to make command/on_message bot
but only we as admin can command the bot not member.

is that possible?

magic stump
#
@client.event
async def on_member_join(ctx, member):

    global hasloo

    channel = discord.utils.get(client.get_all_channels(), guild__name=f'{ctx.guild.name}', name='【✅】weryfikacja-1')

    haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    haslo2 = 5

    hasloo = "".join(random.sample(haslo,haslo2))



    await channel.send(f"**Wyślij komendą** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` why no working?
slate swan
#
@client.command(aliases=['stats', 'bi', 'info'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def botinfo(ctx):
          allmembers = 0
          uptime = datetime.datetime.utcnow() - start_time
          uptime = str(uptime).split('.')[0]
          for guild in client.guilds
              allmembers += guild.member_count
              guilds = len(list(client.guilds))
              before = time.monotonic()
              ping = (time.monotonic() - before) * 1000
              embed = discord.Embed(title=f"**__alone__**", color=color)
              embed.add_field(name="**![note](https://cdn.discordapp.com/emojis/902695950827544779.webp?size=128 "note") name:**",value=f"{client.user.name}", inline=True)
              embed.add_field(name="**![hi](https://cdn.discordapp.com/emojis/902696625007366146.webp?size=128 "hi") guilds:**",value=f"{guilds}", inline=True)
              embed.add_field(name="**![members](https://cdn.discordapp.com/emojis/902688271853822014.webp?size=128 "members") users:**",value=f"{allmembers}", inline=True)
              embed.add_field(name="**![ping](https://cdn.discordapp.com/emojis/902697282003161148.webp?size=128 "ping") ping:**",value=f"{int(client.latency)}ms", inline=True)
              embed.add_field(name="**![uptime](https://cdn.discordapp.com/emojis/902697848422924309.webp?size=128 "uptime") uptime:**",value=f"{date_time}", inline=True)
              embed.add_field(name="**![rules](https://cdn.discordapp.com/emojis/902688036758888479.webp?size=128 "rules") discordpy version:**",value=f"{discord.__version__}", inline=True)
              embed.set_footer(text=f"requested by: {ctx.message.author.name}")
              await ctx.send(embed=embed)```

Why is this sending 3 times
kindred epoch
coral vessel
pliant gulch
#

Because you are iterating through client.guilds

#

If you want it to only run once get rid of the for-loop and dedent the code inside of it

slate swan
#

ohhh

#

or could i just put pass after await ctx.send()?

kindred epoch
magic stump
#
@client.event
async def on_member_join(member):

    global hasloo


    haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    haslo2 = 5

    hasloo = "".join(random.sample(haslo,haslo2))



    await client.get_channel(828011225292079124).send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` this no working too ]
coral vessel
slate swan
#

@commands.has_permissions(adminstator=True)

coral vessel
coral vessel
slim whale
#

how i can make a field for a userinfo that shows the guild permissions? only the highest one, using user.guild_permissions

slate swan
#

anyone familiar with heroku?

slim whale
#

but idk how to do it

hasty iron
hasty iron
#

or i could be wrong

kindred epoch
#

was my favorite chat 😔 so much sarcasm in the title

slim whale
slate swan
hasty iron
#

it doesn’t, it mentions the top role

slim whale
#

i mean this @slate swan

#

its from another bot idk how to do it, but i only want the highest one

kindred epoch
#

wdym highest one

slate swan
#

so role permissions or user permissions

kindred epoch
#

theres no highest permission

slate swan
#

yeah

#

unlesas like admininstaroroasdr

left wind
#

Is it possible to get the id of the message that a bot sends so I can edit it later on

slim whale
kindred epoch
#

isnt that what its sending

#

😐

slate swan
slim whale
left wind
kindred epoch
slate swan
slim whale
left wind
slate swan
#

try that

hasty iron
#

wont work

#

it doesn’t exist

left wind
hasty iron
#

!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.
left wind
slate swan
#

i don't know i don't use it, maybe @hasty iron knows.

hasty iron
#

no, and again that wouldn’t work

left wind
#

oh ok

hasty iron
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
hasty iron
#

thats how you delete a message

slate swan
#

await ctx.message.delete()

left wind
#

whats the * a placeholder for