#discord-bots

1 messages · Page 466 of 1

boreal ravine
#

the time?

brisk helm
#

Why lol

grand anvil
hasty iron
#

read the license

boreal ravine
grand anvil
#

I got the unix time of the time I want to show in the footer

vale root
#

^

grand anvil
#

how to convert unix to datetime

valid niche
#

well that means self.last_msg is None

hollow summit
#
embed.add_field(name="Game", value=ctx.message.author.game)
vale root
valid niche
#

if you look at the logic of your code

vale root
#

mhm

slate swan
boreal ravine
valid niche
#

that message appears when the if not serlf.last_msg is true

slate swan
#

why message

vale root
hollow summit
vale root
#

So that the bot dose not snipe itself

boreal ravine
valid niche
#

those are all attributes and methods of a member

#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").

`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.

`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.

`hash(x)` Returns the member’s hash.

`str(x)` Returns the member’s name with the discriminator.
slate swan
#
@client.event
async def on_guild_channel_create(channel):
      try:
        guild = channel.guild
        logs = await guild.audit_logs(limit=6, action=discord.AuditLogAction.channel_create).flatten()
        logs = logs[0]
        reason = "Created More Channels Then The Limit"
        member = guild.get_member(logs.user.id)
        await member.kick()
        await channel.delete()
      except Exception as e:
        print(e)

The limit is nnot working the moment i make a channel i get kicked how can i fix it or am i doing something wrong

valid niche
boreal ravine
vale root
#

ok so what do i fix?

#

Get rid of self.last)msg?

slate swan
valid niche
slate swan
#

oh

valid niche
#

there's no if statements in there

#

there's nothing being checked

#

it just blindly kicks the person

slate swan
#

time

valid niche
#

how much python have you done before?

slate swan
#

a bit lol

valid niche
#

do you know what an if statement is?

#

and a for loop

slate swan
#

i do know but idk how to make it check the last audit log

gritty meteor
# boreal ravine y add a limit for channels lmfao (un-related)

I guess this is for an anti-raid system, more likely to prevent users from spam-create channels. I'm guessing he wants to check if in a range of seconds how many channels were created, and if that exceeds the limit, the raider would get kicked and the channel would be deleted.

slate swan
#

the time off it

valid niche
#

use for loops and if statements

rare saddle
#

Please help me, look at my code and tell me please why the music stops suddenly? I will throw off the code in DM

valid niche
#

just post your code here

leaden anvil
#

Ok so it gives me the error RuntimeError: Event loop is closed I don't know what to do since I don't were the error starts from plus I am confused with making a secure token btw here is the program ```py
import discord
from discord.ext import commands
from requests import get
import json
import threading
from threading import Thread
import sys
import os

if os.path.exists(os.getcwd() + "/config.json"):

with open("./config.json") as f:
    configData = json.load(f)

else:
configTemplate = {"Token": "", "Prefix": "!"}

with open(os.getcwd() + "/config.json", "w+") as f:
    json.dump(configTemplate, f) 

token = configData["Token"]
prefix = configData["Prefix"]

i=0
client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
print("!!! Bot Is Online !!!\n")

@client.command()
async def hi(ctx):
await ctx.reply("hi")

@client.command()
async def meme(ctx):
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)

runLoop = True
@client.command()
async def inf_meme(ctx):
while runLoop:
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
global i
(i:=i+1)
if i ==(sys.maxsize):
break

@client.command()
async def stop(ctx):
global runLoop
runLoop = False

threading.Thread(target=inf_meme,).start()
threading.Thread(target=meme,).start()

client.run(token)```

slate swan
valid niche
#

naming please

vale root
#

How can i make my embed the avatar of the player being sniped?

unkempt canyonBOT
vale root
#

Using embed.set)thunmbnail()

rare saddle
valid niche
#

are you using v2.0 already?

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
visual island
lament mesa
hasty iron
valid niche
#

you're breaching youtube's TOS, you're breaching discord's TOS and you're breaking copyright @rare saddle so you won't get support here

lament mesa
#

Ig you want to use loop.create_task

#

!d asyncio.loop.create_task

unkempt canyonBOT
#

loop.create_task(coro, *, name=None)```
Schedule the execution of a [Coroutines](https://docs.python.org/3.10/library/asyncio-task.html#coroutine). Return a [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") object.

Third-party event loops can use their own subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task") for interoperability. In this case, the result type is a subclass of [`Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task").

If the *name* argument is provided and not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

Changed in version 3.8: Added the `name` parameter.
leaden anvil
#

thanks but I when I run the code with the bot id it works perfectly fine

hasty iron
#

not awaiting a coroutine doesn't crash your code but it doesnt run the function

gritty meteor
hasty iron
#

and you should use tasks.loop instead

gritty meteor
#

^^ this

hasty iron
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
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/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
rare saddle
unkempt canyonBOT
#

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

valid niche
#

you are not allowed to support people here who break TOS/laws

lament mesa
rare saddle
hasty iron
#

yes

#

you are doing illegal stuff

valid niche
#

violation of TOS of both platforms (youtube and discord) and also a violation of copyright law

lament mesa
#

Not much people read the TOS of services

valid niche
#

making a music bot is like making a radio station. The stations need to get all permissions from every music publisher to use the music in their shows

rare saddle
#

Then why are there such bots as: Rythm, Groovy

valid niche
#

why do you think groovy got shut down?

#

and i doubt rythm will last much longer

#

groovy got a CnD from youtube

rare saddle
#

Groovy works

slate swan
#

There's not much to say really, we're not going to help with a project that uses youtube DL simply because it breaks YouTube's ToS

hasty iron
#

its like making something, another guy copies it and gets popular for it, thats why copyright exists

slate swan
#

Whether YouTube takes action against projects is not our concern, but we won't help people break their ToS

elder python
#

is there any way to know why my bot is extremely slow

hasty iron
#

check for blocking stuff

#

actually iirc, you could enable debug mode of the event loop and it will show you operations that take some time to execute

hollow summit
#

im trying to check if someone has nitro with my bot
but it wont work

    @bot.command()
    async def whois(self,ctx, user: discord.User=None):
        if not user: 
            embed = discord.Embed(title="Your info.", color=0x176cd5)
            embed.add_field(name="Username", value=ctx.message.author.name + "#" + ctx.message.author.discriminator, inline=True)
            embed.add_field(name="ID", value=ctx.message.author.id, inline=True)
            embed.add_field(name="Status", value=ctx.message.author.status, inline=True)
            embed.add_field(name="Highest role", value=ctx.message.author.top_role)
            embed.add_field(name="Roles", value=len(ctx.message.author.roles))
            embed.add_field(name="Joined", value=ctx.message.author.joined_at)
            embed.add_field(name="Created", value=ctx.message.author.created_at)
            embed.add_field(name="Bot?", value=ctx.message.author.bot)
            embed.set_thumbnail(url=ctx.message.author.avatar_url)
            embed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url)
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(title="{}'s info".format(user), color=0x176cd5)
            embed.add_field(name="Username", value=user.name + "#" + user.discriminator, inline=True)
            embed.add_field(name="ID", value=user.id, inline=True)
            embed.add_field(name="Status", value=user.status, inline=True)
            embed.add_field(name="Highest role", value=user.top_role)
            embed.add_field(name="Roles", value=len(user.roles))
            embed.add_field(name="Joined", value=user.joined_at)
            embed.add_field(name="Created", value=user.created_at)
            embed.add_field(name="Bot?", value=user.bot)
            embed.add_field(name = "Nitro",value = user.nitro)
            embed.set_thumbnail(url=user.avatar_url)
            embed.set_author(name=ctx.message.author, icon_url=ctx.message.author.avatar_url)
            await ctx.send(embed=embed)
hasty iron
#

User object has not attribute nitro

#

there is no way to accurately tell if a user has nitro

hollow summit
hasty iron
#

Deprecated since 1.7

#

and it was for user accounts

hollow summit
#

ohh

stiff nexus
#
import menu
c = []
py=1
for emoji in ctx.guild.emojis:
        em=discord.Embed(title=f"Bot Emojis [{len(bot.emojis)}]", colour=0xffffff,description=f"{emoji} | `{emoji.name}` | [`{str(emoji)}`]({emoji.url})")
        try:
          em.set_thumbnail(url=emoji.url)
        except:
          pass
        em.set_footer(text=f"Page {py}/{len(bot.emojis)}",icon_url=ctx.author.display_avatar)
        c.append(em)
        py+=1 
pages =  menu.MyMenu(source= menu.MySource(c,per_page=2), timeout=180.0, clear_reactions_after=True, delete_message_after=True)
await pages.start(ctx)
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/python.py", line 145, in jsk_python
    async for send, result in AsyncSender(executor):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/repl/compilation.py", line 140, in traverse
    async for send, result in AsyncSender(func(*self.args)):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "<repl>", line 15, in _repl_coroutine
    await pages.start(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 967, in start
    await super().start(ctx, channel=channel, wait=wait)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 707, in start
    self.message = msg = await self.send_initial_message(ctx, channel)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/menus/__init__.py", line 963, in send_initial_message
    return await channel.send(**kwargs)
TypeError: send() argument after ** must be a mapping, not NoneType
```help??
spring flax
#

are you doing one emoji per page...?

elder python
#

where do i enable member intents

steep estuary
#

how to make slash commands

#

how i can convert my all commands to slash commands ??

spring flax
spring flax
steep estuary
#

which?

boreal ravine
#

is there a way to get the lyrics to a song im listening on spotify rn using a bot?

boreal ravine
steep estuary
#

ok

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

dapper cobalt
unkempt canyonBOT
elder python
#

is bot.intents.members = True

#

correct

steep estuary
#

k

dapper cobalt
elder python
#

thanks

ionic wadi
#

Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 102, in on_message
users = json.load(f)
File "/usr/local/lib/python3.9/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.9/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Does this mean theres something wrong with my import or with my code?

pale turtle
#

!JSON

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

ionic wadi
#

Ah

#

ok

#

if message.channel.is_private:
AttributeError: 'TextChannel' object has no attribute 'is_private'

#

This function should be working right?

boreal ravine
#

hm

boreal ravine
#

not a thing

ebon island
#

How do I properly call the methods contained within some Cog for example Cog B within the methods of Cog A?

slate swan
unkempt canyonBOT
#

class discord.TextChannel```
Represents a Discord guild text channel.

`x == y` Checks if two channels are equal.

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

`hash(x)` Returns the channel’s hash.

`str(x)` Returns the channel’s name.
rare saddle
#

Please tell me how to get a client_id spotify?

zenith zinc
#

!kiss_command

#

Kiss komand

#

command

#

help plss dm

maiden fable
#

@zenith zinc what?

zenith zinc
#

Kiss command

daring flame
#

Got an issue where bot.getguild(id) returns no guild object.
Any ideas?

maiden fable
daring flame
#
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
GUILD = bot.get_guild(getenv("GUILD_ID"))
print(GUILD)

prints None

zenith zinc
spark dragon
#

Im trying to make my clear command clear for specific users, -clear user amount

how do I make it delete for that user?

maiden fable
#

!d discord.TextChannel.purge use the check kwarg

unkempt canyonBOT
#

await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages
maiden fable
#

Read the examples

fervent surge
#

so I am trying to make slash commands. After 3 hrs of waiting, still nothing, any ideas why?

spark dragon
#

so use bulk?

fervent surge
#

i have the guild thing

maiden fable
maiden fable
spark dragon
maiden fable
spark dragon
daring flame
#

off of slash = SlashCommand(bot, sync_commands=False)

fervent surge
maiden fable
daring flame
fervent surge
#

and the bot has the create command perm

daring flame
fervent surge
spark dragon
fervent surge
#

i kicked it, then reinvite

daring flame
fervent surge
#

i have ben waiting for 3hrs

daring flame
#

it's instant if you use the guild's command sync

fervent surge
#

i have guild thing

#

like aray with guild id

#

its int tho

#

not str

daring flame
#

maybe your function isn't right?
An example would be:

@slash.slash(name="example", guild_ids=[guild.id], description="")
async def example(ctx: commands.Context):
    await ctx.send(response)
fervent surge
daring flame
#

try with them. Since it takes a list

#

but it might also just take an int - but not sure

fervent surge
fervent surge
daring flame
#

check if you really have this line:

slash = SlashCommand(bot, sync_commands=True)
fervent surge
#

i didnt do that

#

i just have a list with 1 id as str now

daring flame
#

it's an int

#

NOT a string

fervent surge
fervent surge
#

i do get this:```python
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at /Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py:415> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn 0.description: Must be between 1 and 100 in length.\nIn 0.options.0.description: Must be between 1 and 100 in length.')>
Traceback (most recent call last):
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py", line 491, in sync_all_commands
raise ex
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord_slash/client.py", line 471, in sync_all_commands
existing_cmds = await self.req.put_slash_commands(
File "/Users/munmun/opt/anaconda3/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 0.description: Must be between 1 and 100 in length.
In 0.options.0.description: Must be between 1 and 100 in length.

lament mesa
#

If you want to display very long text you can use a paginator

fervent surge
lament mesa
fervent surge
#

now it works

#

ugh

#

great

#

thx!

valid galleon
#

does anyone know how i can stop the pychache folder from appearing?

pale turtle
#

This is a question for #python-discussion , last time I asked there I was told it's not recommended

lament mesa
heavy folio
#

would anything happen

valid galleon
valid galleon
lament mesa
lament mesa
valid galleon
#

my code for loading in the cogs:

for cog in listdir(path.join(path.dirname(path.abspath(__file__)), "cogs")):
    if cog.endswith(".py"):
        client.load_extension(f"cogs.{cog[:-3]}")

    else:
        print(f'unable to load {cog[:-3]}') ```
valid galleon
lament mesa
lament mesa
#

Just let it be where it is.

slate swan
valid galleon
slate swan
#

(Not that it makes a difference)

valid galleon
#

AttributeError: module 'discord.ext.commands.errors' has no attribute 'ExtensionFailed'

#

yeah

#

error

lament mesa
valid galleon
#

i switched from d.py to pycord, but i dont think thats causing the error

#

according to it, its this line thats causing the error:
client.load_extension(f"cogs.{cog[:-3]}")

hasty iron
#

thats why forks are bad

valid galleon
#

bru

zenith zinc
#

Economy bot

#

who know make economy bot

#

dm pl

boreal ravine
#

make. it. ur. self.

maiden fable
#

y. e. s.

We are just here to help you fix bugs that u may encounter while make it or clear your doubts, not make it for you

upbeat otter
#

Guys, how do i add a GIF to an embed?

#

what attribute do i use?

maiden fable
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
upbeat otter
#

thanku

#

Why does it not load the GIF?

#

its just loading

#

and then becomes a poop 🥲 sign

maiden fable
#

Either the URL is wrong else is a discord issue

upbeat otter
#

like one month back, i tried the same

#

and now still it doesnt work

#
@client.command()
async def emt(ctx):
  e = discord.Embed(title="trial Embed", description=" ")
  e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
  await ctx.send(content=None, embed=e)
maiden fable
#

Seems like a discord issue

upbeat otter
#

ye

#

thanx

upbeat otter
#

gifs?

maiden fable
#

Seems like it

#

Wait

#

@upbeat otter

#

It's my mistake

upbeat otter
#

uh

maiden fable
#

U gotta set the description to the url

upbeat otter
#

i dont understand 🥲

#

ah

maiden fable
#

!d discord.Embed.description

unkempt canyonBOT
upbeat otter
#

name="hvrfbwlrf", url="https://rhwbkrw"

#

Like this?

maiden fable
#

No

#

Embed(description=url)

upbeat otter
#

ah

#

thanku

fervent surge
#

when I am using ctx : SlashContext, I am getting this error when using ctx.message.author:python AttributeError: 'NoneType' object has no attribute 'author'

opaque trail
#

should be ctx.author not ctx.message

#

.author

fervent surge
frosty prairie
#

Uh..message sent by bot

slate swan
zenith zinc
#

change prefix with chat command pls help dm me

slate swan
#

someone tell me how to make an embed?

zenith zinc
#

!embed

hoary gust
#

Guys it's possible to use any frontend framework with django right?

zenith zinc
slate swan
#

ok

#

Google is your friend

#

¯_(ツ)_/¯

zenith zinc
#

😦

slate swan
#

Just stop

zenith zinc
#

Helppp dm pl

slate swan
#

d ¯_(ツ)_/¯

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

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

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

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

jeez

zenith zinc
#

yes

hoary gust
#

Lol

zenith zinc
#

mmm

#

script for change prefix with chat command pls dm mee help

slate swan
#

Use a database

hoary gust
#

@zenith zinc make it urself

slate swan
#

We won't code for you

#

We can help you with what you've done so far

zenith zinc
#

ok

open forge
#

I figured out the problem. I was using a cog listener for command invocation, but I forgot that listeners won't override the internal library handling of on_message, so I was creating a CustomContext object and invoking a command with it, while the library was creating a normal Context object and invoking a command with it. That's why it looks like the command worked fine, when really it was just being ran twice.

stark bobcat
#

hi

slate swan
#

elo

stark bobcat
#

hey

hoary gust
#

@stark bobcat hi bud

waxen granite
stark bobcat
storm zodiac
#

can i ask here if people want to contribute in the creation of my bot ?

slate swan
#

which is better sublime or vsc?

#

Then you should've seen there's no ctx.message.author

clever wind
#
class Lobby:
  def __init__(self, lobby_number, queue_channel_id, Team_A_channel_id, Team_B_channel_id):
    
    queue_channel = client.get_channel(883963916915453962)
    Team_A_channel = client.get_channel(Team_A_channel_id)
    Team_B_channel = client.get_channel(Team_B_channel_id)

    queue_channel_members = queue_channel.members
    queue_channel_members_mention = []
    for member in queue_channel_members:
        queue_channel_members_mention.append(member.mention)

    @client.group(invoke_without_command=True)
    async def lobby(ctx):
      ctx.send("Lobbies Online.")

    @lobby.command()
    async def start(ctx):
        random.shuffle(queue_channel_members_mention)

        team_a = queue_channel_members_mention[len(queue_channel_members_mention) // 2:]
        team_b = queue_channel_members_mention[:len(queue_channel_members_mention) // 2]

        embed_lobby1 = discord.Embed(title="Teams")
        embed_lobby1.add_field(name="Team A", value="\n".join(team_a), inline=True)
        embed_lobby1.add_field(name="Team B", value="\n".join(team_b), inline=True)
        await ctx.send(embed=embed_lobby1)

it says nonetype doesn't have the attribute members

waxen granite
#

Command raised an exception: TypeError: 'NoneType' object is not subscriptable what does this mean?

slate swan
#

Object is None

#

And you're trying to get an element from it or manipulate it

waxen granite
#

Okay

clever wind
#

queue_channel shouldn't be a nonetype

slate swan
#

For what line do you get the error

clever wind
#

3rd line

stark bobcat
#

How do i read a user's dm

slate swan
#

Bot might not have the channel in cache and therefore can't see it

clever wind
slate swan
#

await it

#

await client.fetch_channel....

clever wind
slate swan
#

Nope

clever wind
# slate swan Nope

await out of async function, then when do use async it says: init() should return None, not 'coroutine'

slate swan
#

Wait, why are your commands even in the init function?

clever wind
#

um thats weird now that i see it

frosty prairie
#

didnt get

stark bobcat
#

how can i print the message the has user sent to the bot

slate swan
#

So simply message.content

stark bobcat
slate swan
#

It is

storm zodiac
slate swan
#

E is capital

hoary gust
#

@storm zodiac anyone u want to

#

But at ur own risk

slate swan
#

As I said, it's Embed and not embed

stark bobcat
#

like in bot dms

slate swan
#

It's the same event

#

Same event gets triggered

stark bobcat
#

oh

#

oh

#

ok thanks

slate swan
#

Then you can just check the channel of the message to see if it's in private messages

hoary gust
#

If (message.channel.type) == "private"

slate swan
#

Nope

hoary gust
#

Maybe

slate swan
#
if isinstance(message.channel, discord.channel.DMChannel):
hoary gust
#

I am a bit rusty

slate swan
#

Check the object if it's an instance of the DMChannel object

hoary gust
#

@slate swan well that's not foor event

slate swan
#

It is?

hoary gust
#

No it's a cmd error handler

slate swan
#

No

#

It's Python knowledge

storm zodiac
slate swan
#

embed=embed when sending the embed

#

await channel.send(embed=define the embed)

hoary gust
#

!rule 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

hoary gust
#

@storm zodiac I don't think u want to get warned by mods bud

slate swan
#

It is

storm zodiac
#

how is it add

slate swan
#

Kind of at least

hoary gust
#

It is

#

Delete it

storm zodiac
#

i have seen other people requesting

storm zodiac
hoary gust
#

Else we have to ping mods

storm zodiac
hoary gust
#

!rule 6@storm zodiac

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

hoary gust
#

!rule 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

storm zodiac
#

how is it advertising ?

hoary gust
#

It is

slate swan
#

Just leave it

hoary gust
#

It's not allowed

slate swan
#

By now the message can't be seen anymore anyways

hoary gust
#

Mod here

#

Scofflaw

blissful lagoon
#

It's understandable that you thought to look here for help, but unfortunately we don't allow advertising even for personal projects

slate swan
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

You're missing f

#

Before the ""

hoary gust
#

Thanks scofflaw

storm zodiac
#

afaik advertising meant, "use my lib" - "i will pay you" - "this other thing is better i made it"

slate swan
#

You may want to listen to the moderator though right?pithink

lone aurora
#
@client.command(aliases=['ac'])
async def announce(ctx, message):
    embed = discord.Embed(
        title = '',
        description = '',
        colour = ctx.author.colour  
        
    )

    embed.set_footer(text='By oSeatch#6969')
    embed.set_author(name=ctx.message.author)
    embed.add_field(name='News', value=message , inline=False)

    await ctx.send(embed=embed)
    await ctx.message.delete()``` My code is supposed to be used in this way

`.announce This is a test`, it will embed `This Is A Test` but right now what it does is emebed `This` because value=message only takes `This` from the message. My question is how do i make take the entire sentence?
slate swan
#

Use *

lone aurora
slate swan
slate swan
slate swan
hoary gust
#

^

lone aurora
#
@client.command(aliases=['ac'])
async def announce(ctx, *, message):
    embed = discord.Embed(
        title = '',
        description = '',
        colour = ctx.author.colour  
        
    )

    embed.set_footer(text='By oSeatch#6969')
    embed.set_author(name=ctx.message.author)
    embed.add_field(name='News', value=message , inline=False)

    await ctx.send(embed=embed)
    await ctx.message.delete()``` this should work?
slate swan
#

Should, yes

lone aurora
#

al right ill test it

slate swan
#

Try it and see ¯_(ツ)_/¯

hoary gust
#

Hey Krypton

lone aurora
#

Wow thanks alot @slate swan

slate swan
#

No problem CS_PepeTip

#

ctx.author.mention

lone aurora
hoary gust
#

@hollow iron ctx.author.mention

lone aurora
#

wrong reply ._.

slate swan
#

If you use it once it's redundant code though, but yes you can

hoary gust
#

@slate swan Hey bud

slate swan
#

Yes?

frosty prairie
#

..

slate swan
#

Use fetch_member and save it in a variable, and then use .send on it

hoary gust
#

Well tbh I once advertised my bot in this server and I don't even know that I was warned and after 3 months when I was talking with a mod in modmail he told me I was warned once @slate swan

#

🤣🤣🤣

slate swan
#

Unlucky I guess

#

Just put the id

hoary gust
#

@hollow iron api call bud

slate swan
#

Without id=

hoary gust
#

Don't use

frosty prairie
hoary gust
#

Don't use fetch

slate swan
#

Will have to, if you don't have the members intent enabled

manic path
#

Hey, what does this error mean?

Message: 'Unclosed client session\nclient_session: <aiohttp.client.ClientSession object at 0x7fbcded0d250>'
Arguments: ()
2021-09-12 21:35:46,160 - asyncio - ERROR - Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7fbcded0d250>
slate swan
hoary gust
#

Unknown emoji

#

Means the bot didn't find it

frosty prairie
#

but .. i tried both ways

#

unicode and discord name

slate swan
#

Make sure the bot is in the server where the emote is

hoary gust
#

^

frosty prairie
#

i tried a default emote 🤙

#

this one ..

slate swan
#

Just put it normally in the string?

#

\🤙

frosty prairie
#

yea .. i did

slate swan
#

Copy paste this

#

Works fine

frosty prairie
#

how u got this type of emoji...

#

🤙

#

:/

slate swan
#

?

cloud dawn
#

Use both get and fetch.

slate swan
#

\🤙

frosty prairie
#

ur emoji small

slate swan
#

Like that

frosty prairie
#

\🤙

slate swan
#

Yup

frosty prairie
#

ohh

cloud dawn
#

!charinfo 🤙

slate swan
#

Copy paste that in your code

unkempt canyonBOT
cloud dawn
#

Or use the unicode ^

frosty prairie
frosty prairie
leaden anvil
#

Hey this should help ```py
from discord.ext import commands
import discord

bot = commands.Bot(command_prefix='!')

@bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)

bot.run("TOKEN")``` original post was from: https://stackoverflow.com/questions/52343245/python-dm-a-user-discord-bot

cloud dawn
#

Hello

frosty prairie
#

he!!o

hasty iron
#

send_message is no longer a thing

cloud dawn
#
vaprant_id = guild.get_member(672580539513045013) or await bot.fetch_member(672580539513045013)
lone aurora
#

for the administrator permission would it be ctx.author.guild_permissions.administrator

leaden anvil
hasty iron
#

not Bot

cloud dawn
hoary gust
hasty iron
#

it was a thing some time ago

hasty iron
#

but it was removed

lone aurora
#

thanks

leaden anvil
#

Can anyone help me with this problem ? Ok so I have fixed my previous error but now it gives me prefix = configData["Prefix"] KeyError: 'Prefix' the prefix that I set is in the config file which is {"Token": "<Bot Token>", "prefix": "!"} here is the code ```py
import discord
from discord.ext import commands
from requests import get
import json
import threading
from threading import Thread
import sys
import os

if os.path.exists(os.getcwd() + "/config.json"):

with open("./config.json") as f:
    configData = json.load(f)

else:
configTemplate = {"Token": "", "Prefix": "!"}

with open(os.getcwd() + "/config.json", "w+") as f:
    json.dump(configTemplate, f) 

token = configData["Token"]
prefix = configData["Prefix"]

i=0
client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
print("!!! Bot Is Online !!!\n")

@client.command()
async def hi(ctx):
await ctx.reply("hi")

@client.command()
async def meme(ctx):
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)

runLoop = True
@client.command()
async def inf_meme(ctx):
while runLoop:
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content,)
meme = discord.Embed(title=f"{data['title']}", Color = discord.Color.random()).set_image(url=f"{data['url']}")
await ctx.message.channel.send(embed=meme)
global i
(i:=i+1)
if i ==(sys.maxsize):
break

@client.command()
async def stop(ctx):
global runLoop
runLoop = False

threading.Thread(target=inf_meme,).start()
threading.Thread(target=meme,).start()

client.run(token)``` also error occurs in line 22

hasty iron
#

look at the difference

leaden anvil
leaden anvil
boreal ravine
#

whats bot for

upbeat otter
#

why is this not working 🥲

@client.command()
async def emt(ctx):
  e = discord.Embed(title="trial Embed", description=" ")
  e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
  await ctx.send(content=None, embed=e)
boreal ravine
#

what u tryna do?

vestal owl
#
if message.content.lower() == 'registration complete':
                fetched = ctx.guild.get_member(881081223533977630)
                print(fetched)
                guild = discord.Guild
                await my_channel.send('All users registered!')
                overwrites = {
                def = guild.default_role: discord.PermissionOverwrite(read_messages = False),
                guild_me = guild.me: discord.PermissionOverwrite(read_messages = True)
                }
                if message.author.id not in reg_user:
                    await my_channel.set_permissions(ctx.guild.default_role, overwrite = overwrites)```
so I've almost got the code working, its just that ``read_messages = False`` is True also for the bot, meaning it can't speak in the channel, how do I get around this?
upbeat otter
#
@client.command()
async def emt(ctx):
  e = discord.Embed(title="trial Embed")
  e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
  await ctx.send(embed=e)
```like this?
upbeat otter
#

thenx

#

still not working

vestal owl
hasty iron
#

that makes it clear that you don't know basic python

boreal ravine
vestal owl
upbeat otter
# boreal ravine it should work
@client.command()
async def emt(ctx):
  e = discord.Embed(title="trial Embed")
  e.set_image(url="https://tenor.com/view/kermit-suicide-flip-jump-crash-gif-5140737")
  await ctx.send(embed=e)
``` This GIF doesnt load, the embed is successfully sent
hasty iron
cloud dawn
#
def = guild.default_role: discord.PermissionOverwrite(read_messages = False),
                guild_me = guild.me: discord.PermissionOverwrite(read_messages = True)
                }
``` this is art
upbeat otter
vestal owl
#

i do know basic python

boreal ravine
hasty iron
#

and you need an instance of Guild not the class itself

upbeat otter
hasty iron
boreal ravine
#

where the comma's

#

wait you can set footers in the variable too?

vale root
#

How can i make my bot put a emote in the embed?

brisk fiber
#

also, some fields in an embed need to be added via the embed.set_x methods

boreal ravine
vale root
#

For ex: join Flashing

vale root
#

So I just get the id and put it in?

hasty iron
#

if you're asking about invalid syntax errors, you should review basics

frosty prairie
#

is there smth like ..
bot.wait_for('reaction')?

boreal ravine
vale root
boreal ravine
#

???

frosty prairie
boreal ravine
#
await message.channel.send
vale root
#

So i would do

embed = discord.Embed(title = f"(the id) baaala")
?

boreal ravine
#

message.channel.send

frosty prairie
frosty prairie
#

thats*

vale root
boreal ravine
vale root
#

all i can get is :blaa:

frosty prairie
#

idk y reply

brisk fiber
#

you'd have to do my_user = bot.get_user(your_user_id) and then my_user.send(blah)

boreal ravine
vale root
#

ok thx

boreal ravine
brisk fiber
#

message.channel.send() just sends your message to whatever channel the original message was sent in

#

so you have to get the user object of the user you want to DM, then send it to them via the .send() method on that object

vale root
#

oh wait hang on

boreal ravine
#
member = 696969696969696969
await member.send(672580539513045013, embed= discord.Embed(title="Personal Info Detected!", description=f"{message.author} was banned for an attempt at leaking personal information!", footer="{message}" color=0xff0000))
``` @hollow iron dis maybe
brisk fiber
vale root
#

nvm i got it

upbeat otter
#

set_image is still not loading the GIF

boreal ravine
boreal ravine
brisk fiber
#

an int has no method .send()

upbeat otter
boreal ravine
upbeat otter
#

woh

boreal ravine
#

dont use tenor

upbeat otter
#

I see

boreal ravine
upbeat otter
#

giphy?

vale root
#
@commands.command(name="ssuvote")
    async def ssuvote(self,ctx):
        embed = discord.Embed(title = f"SSU VOTE", description =f"Vote With the ![Yes](https://cdn.discordapp.com/emojis/860879912955805696.webp?size=128 "Yes") mark if you plan on attending."  "\n" " Put a ![No](https://cdn.discordapp.com/emojis/860879881653977140.webp?size=128 "No") if you can not join." "\n" "If you vote with the check you must join when ssu opens if not you will be warned")
        embed.set_thumbnail(url = 'https://images-ext-2.discordapp.net/external/jftnVFITYRGaMwbf6aY7Qutqp6Q_2gA4v72nXBbpALg/%3Fsize%3D512/https/cdn.discordapp.com/icons/857793161370533938/c38dde5d462235e12a3e10a2dc789dc6.png?width=461&height=461')
        await ctx.send(embed=embed)
boreal ravine
vale root
#

let me check i think so

brisk fiber
# boreal ravine true

you were calling .send() on member but member is just the userid, not the user object lol

vale root
#

Yea it is

boreal ravine
vale root
#

wait let me check again

boreal ravine
#

wait can u put emojis in custom descriptions?

brisk fiber
frosty prairie
#

IS THERE SMTH LIKE
bot.wait_for('reaction')

#

?

brisk fiber
#

idk why it didn't work with just the id and stuff but

brisk fiber
#

uh hang on

boreal ravine
#

Maybe just make a variable with the emoji id and use an f string

cloud dawn
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cloud dawn
#
def check(reaction, user):
   return user == message.author and str(reaction.emoji) == '👍'
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
brisk fiber
vale root
#

I got it

brisk fiber
#

ah alright nice

vale root
#

thanks though

brisk fiber
#

no worries haha

vestal owl
brisk fiber
#

i've gtg in a minute but if you ask your question someone will probably be able to help!

vestal owl
#
await my_channel.send('All users registered!')
                overwrites = {
                guild.default_role: discord.PermissionOverwrite(read_messages = False),
                guild.me: discord.PermissionOverwrite(read_messages = True)
                }
                if message.author.id not in reg_user:
                    await my_channel.set_permissions(ctx.guild.default_role, overwrite = overwrites)
                    print('Non registered users cannot speak')```
slate swan
#

code?

#

oh

vestal owl
slate swan
#

myEmbed.add_field(name='Message:', value=...)
@hollow iron

vestal owl
slate swan
#

put its id in reg_user ig

vestal owl
#

tried that though

slate swan
#

guys how can i get number of people in guild in {}?

#

!d discord.Guild.member_count

unkempt canyonBOT
#

member_count```
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/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
slate swan
#

or do you mean

#

!d discord.Guild.members

unkempt canyonBOT
vestal owl
#

discord.guild.members

slate swan
#

note that discord.Guild has to be replaced with a guild object

vestal owl
#

like ctx right?

slate swan
wide dust
slate swan
#

like ctx.guild

vestal owl
#

yep

slate swan
#

oh

#

I'm stupid

#

message.guild.members?

#

member.guild.members

slate swan
#

what

slate swan
#

but your problem is with pillow

#

so you may send your code

#

and the error

#

it don't work doesn't help me in helping you

slate swan
#

but cant figure out how to def how many members are in guild

#

member.guild.members should work

#

send the error

#

vaprant_id is Nonetype

#

it returned nonetype

#

is the guy you want to get in a server with your bot?

vestal owl
#

where is the variable {my_Embed}

#

can you show that part too

slate swan
#

then use
discord.Guild.get_member

#

and you send embeds like
await member.send(embed=myEmbed)

#

Yup

lone aurora
#
        await ctx.send(random.choice(variable))``` can someone tell me what im doing wrong here
lone aurora
#

i had it written but i deleted it and saved and now i am forget..

slate swan
#

What is variable

#

Should be something like a list

lone aurora
#

yes

#

a list of pictures

slate swan
#

Then we'd need the error

lone aurora
slate swan
#

🤦‍♂️

vestal owl
#

import random

slate swan
#

Yup

lone aurora
#

ight

slate swan
#

but.... a list of pictures?

#

wouldn't it be in the file kwarg then?

#

!d discord.TextChannel.send

unkempt canyonBOT
#

await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=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/stable/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/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
slate swan
#

To upload a single file, the file parameter should be used with a single File object. To upload multiple files, the files parameter should be used with a list of File objects. Specifying both parameters will lead to an exception.

lone aurora
#

also thanks it worked

slate swan
#

yes, guild.get_member(id)

maiden fable
#

Good job on helping people pithink

slate swan
#

hi

maiden fable
#

Hi

vestal owl
#
if message.content.lower() == 'registration complete':
                await my_channel.send('All users registered!')
                perms = my_channel.overwrites_for(ctx.guild.default_role)
                if ctx.guild.default_role not in reg_user:
                    perms.send_messages = False
                    await my_channel.set_permissions(ctx.guild.default_role, overwrite = perms)
                    print('Non registered users cannot speak')```
#

ok this is seriously not working

slate swan
#

you forgot the id part...

slate swan
#

oof, I only read the last line

#

but like

#

you used the class

#

not an instance of it

#

discord.Guild always has to be replaced with a guild instance

#

message.guild for example

vestal owl
# slate swan what's the problem with it

what it does is that it prevents @ everyone from speaking in the channel, but then it also prevents the bot from speaking in the channel which is what Im trying to undo

slate swan
#

why don't you give it permission in discord

vestal owl
#

it has administrative permissions

slate swan
#

then it's impossible to prevent it from anything...

vestal owl
#

but this is an overwrite so no matter what happens, the bot is affected

vestal owl
neat birch
#

Anyone Know How To Make A Bot Command Like If We Do - .delete [channel name] ( not channel mention) it deletes every channel in the server with that name

slate swan
#

have you tried writing something there with the bot?

#

has it thrown an error?

#

wrong id?

#

no intents?

#

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

vestal owl
slate swan
#

oof

vestal owl
#

i forgot to turn administrator on

#

LMAO

neat birch
slate swan
#

that's a bru moment

vestal owl
#

i've been drilling at that for 2+ hours

#

this happens a lot

slate swan
#

should I ask once again

#

have you enabled intents?

#

are you sure you have the right id?

#

are you sure the bot is in a server that the person's in?

lone aurora
#

Can i not make error codes in cogs? like @test.error

slate swan
#

you absolutely can

lone aurora
#

raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.math' raised an error: AttributeError: 'function' object has no attribute 'error'

#
import discord
from discord.ext import commands

class math(commands.Cog):
    
    def __init__(self, client):
        self.client = client


    @commands.command
    async def add(self, ctx, num1:int, num2:int):
        await ctx.send(f"__{num1}__ + __{num2}__ = **__{num1 + num2}__**")

    @add.error
    async def add_error(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            em = discord.Embed(title=f"Error!!!", description=f"Incorrect Syntax. Please use **&add <first number> <second number>**", color=ctx.author.colour) 
            await ctx.send(embed=em)


def setup(client):
    client.add_cog(math(client))```
slate swan
#

hm

lone aurora
#

im trying to setup cogs and its my first time doing it, i have no clue where im going wrong

slate swan
#

oh bru

lone aurora
spring flax
#

what

#

look at your code again

lone aurora
#

stop being so good diabolical

#

actually, be the best so u can fix my codes, thanks ;DD

slate swan
#

!d discord.Guild.get_member

unkempt canyonBOT
slate swan
#

yeah, idk

#

intents are both in dev portal and in the code enabled?

#

stop putting discord in your code

#

bot tab

#

there, under
Privileged gateway intents

#

instantly

#

and guild is lowercase there

#

message.Guild
message.guild ✅

#

otherwise it's even worse

#

server members intent enabled

#

now try with message.guild.get_member

#

guild

last moss
#

!paste

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

slate swan
#

show me your imports and the bot declaration

#

@hollow iron

#

now the bot = commands.Bot stuff

#

then client

#

client doesn't take intents.....

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").
slate swan
#

oh, it actually does

#
intents = discord.Intents.default()
intents.members = true

client = discord.Client(intents=intents)```
#

or just Intents.default()

#

since you've imported it

#

you can

#

you can delete the from discord import Intents
and paste this in your code

#

then it should work

#

if not, I'm done

#

you're welcome

crimson cliff
#

Hi Guys
I made a simple bot
But Their Command doesn't work
Even I run python program in VS Code
Still...

#

Anyone Help

#
import os 
import discord
from discord.ext import commands
import random

client = discord.Client()

client = commands.AutoShardedBot(command_prefix="$")

@commands.Bot
async def on_ready():
    print('Bot is ready. ')

@client.command()
async def ping(ctx):
    em = discord.Embed(title="Pong!", color=discord.Color.dark_blue())
    em.add_field(name="bot ping", value=f"{round(client.latency * 1000)}ms")
    em.set_footer(text="ping")
    await ctx.send(embed=em)

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ['It is certain.', 'It is decidedly so.', 'Without a doubt.', 'Yes - definitely.',
                 'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
                 'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
                 'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My reply is no.',
                 'My sources say no.', 'Outlook not so good.', 'Very doubtful.']
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#

This is my code

#

did not work for while
Someone pls help

#

Hlo
Anyone help

#

@copper quartz

cloud dawn
#

Please don't ping random people especially staff.

crimson cliff
crimson cliff
cloud dawn
#

Because typhinting only converts an object to a datatype

brisk fiber
#

if you want it to be optional you'd have to make it a keyword argument with default value None

#

or whatever default you want

spring flax
#

if they are all strings, you can't do that

brisk fiber
#

i think you can have an embed without a description, yeah

#

but i'm not sure

spring flax
#

you cannot have a typing.Optional in between arguments if they're all strings

#

but what you can do is

#

use each arg with " "

#

like

#

"this" "is" "a" "example"

cloud dawn
#

Slash commands allow optional kwargs that allow you to customize it better and have it more user friendly.

crimson cliff
#

there is no error
But when i commands
No reply

brisk fiber
brisk fiber
#

yeah

cloud dawn
#

Do you want to create embeds?

#

Yeah i'd recommend slash

spring flax
#

yes

#

wait

#

nevermind, that's not what you want

crimson cliff
#

@brisk fiber this error came

spring flax
#

if you want to have an optional arg in between a list of args typehinted to strings, there's no way afaik

#

(considering you don't want slash commands)

cloud dawn
open forge
cloud dawn
crimson cliff
open forge
crimson cliff
brisk fiber
#

oh i misread your code lol

#

you defined client as a Client object and then reassigned it to an AutoShardedBot right after

cloud dawn
thorny pagoda
#

heeyy

thorny pagoda
#

hiiiii

brisk fiber
#

you do run your bot, right?

brisk fiber
#

bot.run(token)

thorny pagoda
#

hiiiu

crimson cliff
#

the mark i did I need to change that Client into bot?

crimson cliff
crimson cliff
cloud dawn
brisk fiber
#

^

waxen granite
#

in last line

brisk fiber
#

looks like embedchannels is an int

crimson cliff
# cloud dawn You can just do replace all
import os
import discord
from discord.ext import commands
import random
from keep_alive import keep_alive

bot = commands.Bot()

bot = commands.AutoShardedBot(command_prefix="$")


@bot.event
async def on_ready():
    print('bot is ready.')


@bot.command()
async def ping(ctx):
    em = discord.Embed(title="Pong!", color=discord.Color.dark_blue())
    em.add_field(name="bot ping", value=f"{round(client.latency * 1000)}ms")
    em.set_footer(text="ping")
    await ctx.send(embed=em)

@bot.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = ['It is certain.', 'It is decidedly so.', 'Without a doubt.', 'Yes - definitely.',
                 'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
                 'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
                 'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My reply is no.',
                 'My sources say no.', 'Outlook not so good.', 'Very doubtful.']
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')


@bot.command()
async def hello(ctx):
  await ctx.send("Hello")
 

@bot.event
async def on_member_join(member):
    print(f'{member} has joined a server.')

@bot.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

Fine?

waxen granite
cloud dawn
crimson cliff
#

same error

crimson cliff
cloud dawn
#

Because you need to add the arg command_prefix

boreal ravine
#

what does sharding do? @crimson cliff

cloud dawn
#

and remove bot = commands.AutoShardedBot(command_prefix="$")

round quarry
#

Why is it that when I execute a file, for example "ban.py", I can only execute the "ban" command, and when I execute the other files, such as "kick.py", only "kick" is executed?
I explain? shipit

brisk fiber
boreal ravine
#

@round quarry because u can only run 1 at a time

crimson cliff
brisk fiber
round quarry
waxen granite
#

how do i convert a int obj in a channel obj?

crimson cliff
boreal ravine
brisk fiber
#

i don't think you want an AutoShardedBot while you're still learning the fundamentals of discord.py

boreal ravine
#

He didn't reply.

boreal ravine
#

r u blind

crimson cliff
vale root
#
   @commands.command(name="Say")
    async def say(self, ctx,*, message=None):
        await ctx.send(message)

How do i make the bot delete what the person said?

#

So it delete the say command

#

So all you see is what the bot said

boreal ravine
crimson cliff
boreal ravine
cloud dawn
boreal ravine
#

its in ur code right?

vale root
#

thx

boreal ravine
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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
crimson cliff
boreal ravine
#

@crimson cliff wym "no"?

crimson cliff
boreal ravine
#

its right there in ur code and im asking what doed sharding do?

boreal ravine
crimson cliff
boreal ravine
vale root
#

For my snipe command how can i make it show the person being sniped's avatar?

@commands.command(name="Snipe")
    async def snipe(self, ctx: commands.Context):
        if not self.last_msg:
            await ctx.send("There is no message to Snipe!")
            return

        author = self.last_msg.author
        content = self.last_msg.content

        embed = discord.Embed(title=f" Message from {author}", description=content)
        await ctx.send(embed=embed)
#

embed.set_thumbnail(url {author.avatar})??

boreal ravine
#

did u try it yet?

vale root
#

What i just wrote?

boreal ravine
#

yes

vale root
#

no

#

let me try it

boreal ravine
#

ok

vale root
#

When I add that the command dose not work

leaden anvil
#

Ok , is there any web app server with free hosting for discord bots or any other thing and not like free trail but free to use. Please tag me if u want to reply.

cloud dawn
#

author.avatar_url

vale root
#

where do i put that

#

Oh in the ()

vale root
#

still dose not make the command work

cloud dawn
#

Show me the syntax

vale root
#

There is no error

#

It just dose not work

#

the rest of the cmds work not that one

leaden anvil
cloud dawn
leaden anvil
vale root
#

When you open your file it will show the power shell and open the terminal

#

So if you make that terminal run when you open your pc

vale root
#

idk if it works

#

Sounds like it should lol

vale root
leaden anvil
vale root
#

mhm

hollow agate
#
@client.event
async def on_message_delete(message):
    logchannel = client.get_channel(872911089258598421)
    await logchannel.send(f'Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. \n**Content**: {message.content}')``` How can I make this tell me how long the message was in the channel for before it was deleted?
#

Like for example, it was deleted 4 seconds after the message was sent, it would say (4 seconds after message was sent)

waxen granite
#

ValueError: Circular reference detected what does this means?

slate swan
unkempt canyonBOT
brave phoenix
#
  • current time
slate swan
#

Compare to current time

#

Yep yep

drowsy dust
#
@client.command()
async def steal(ctx, name=None, emoji:discord.Emoji=None):
  if name==None:
    name=emoji.name
  if len(ctx.message.attachments) > 0 and emoji==None:
    stolen=ctx.message.attachments[0]
    image = await stolen.read()
    await ctx.guild.create_custom_emoji(
      name=name, 
      image=image
      )
    await ctx.send(f'Emoji {stolen} added with the name "{name}"')
  elif emoji.animated:
    emoji_url = emoji.url
    new_emoji = requests.get(emoji_url)
    await ctx.guild.create_custom_emoji(
      name = name,
      image = new_emoji.content()
        )
  elif emoji != None:
    image = await emoji.url.read()
    print(image)
    await ctx.guild.create_custom_emoji(
      name=name,
      image=image)
    await ctx.send(f'{emoji} added with the name "{name}".')        
#

Ignoring exception in command steal:
Traceback (most recent call last):
  File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "d:\INFORMATICA\Discord bot\sefu.py", line 348, in steal
    elif emoji.animated:
AttributeError: 'NoneType' object has no attribute 'animated'

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

Traceback (most recent call last):
  File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\AppData\Roaming\Python\Python39\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: 'NoneType' object has no attribute 'animated'```
#

help please

full lily
#

emoji is None

waxen granite
#

no errors

full lily
#

banList must be empty

waxen granite
#

ye

#

should i keep a check for it?

slate swan
#

anyone know whats wrong here coded this ages ago

@bot.command(
  name="kick",
  help="kick mentioned user",
  usage="prefix kick <@member> [reason]"
)
async def _kick(ctx, member: discord.Member, *, reason=None):
  await member.kick(reason=reason)
  await ctx.message.delete()

@bot.command(
  name="ban",
  help="ban mentioned user",
  usage="prefix ban <@member> [reason]"
)
async def _ban(ctx, member: discord.Member, *, reason=None):
  await member.ban(reason=reason)
  await ctx.message.delete()
wary ravine
cloud dawn
#

If a list is empty you can just do if

#
if banList:
  # banList is defined
else:
  # banList is None (empty)
waxen granite
#

i just want to send the else part, if the banlist is empty

unkempt canyonBOT
#

discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the `Client.max_messages` attribute or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
waxen granite
cloud dawn
wary ravine
cloud dawn
#

So this says: if banList is empty or None

#

!e ```py
x = None

if not x:
print('True since we applied not so False will become True')

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

True since we applied not so False will become True
slate swan
#

thats all i have and it just doesnt work

#

idk why

kindred epoch
#

does it show an error?

slate swan
kindred epoch
slate swan
#

i have perms tho

kindred epoch
#

?

#

you're not the bot

slate swan
#

ooh ye

kindred epoch
#

it cant ban u

#

or its missing ban_members perms

slate swan
#

ye im just dumb

#

it does work lmao

#

sry bout that

waxen granite
#

should i add return after if not banList?

cloud dawn
#

I have no idea what this is doing.

kindred epoch
#

what are you trying to do?

waxen granite
#

if not banlist check if there is a ban list in the server when a member leaves the server.

kindred epoch
#

?

waxen granite
#

for ban in ban list check 2 things when banlist exists
` - if the member is in the banlist it sends a msg saying member was banned
else
member left the sever

kindred epoch
#

so you want to send a message that a member left if a member gets banned?

wary ravine
#

how many instances are you running

waxen granite
#

1

#

figured , ty guys

#

how can i make an arg optional ?

wicked atlas
hasty iron
#

that’s not true

#

you give it a default value, or in dpy you typehint it as Optional

round quarry
#

What happens is the following, it turns out that I have several .py files, for example: "avatar.py", "invite.py", "purge.py", etc. And when executing a file, only that file can be executed, for example I execute the avatar.py file, but only that one works, and the other files do not. I explain?

wicked atlas
hasty iron
#

do you know what a kwarg is

wary ravine
hasty iron
#

its keyword argument

wicked atlas
#

Well, I guess you could say keyword parameter

hasty iron
#

everything after , *, is a kwarg

#

giving something a default value doesn’t make it a kwarg

#

!e ```py
def foo(*, a): pass
foo()

unkempt canyonBOT
#

@hasty iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: foo() missing 1 required keyword-only argument: 'a'
wicked atlas
#

Hmm, interesting

lofty mulch
#

My main file isn't showing any output

#

!paste

waxen granite
#

is there a way to get all the cogs?

#

a list of them

hasty iron
#

!d discord.ext.commands.Bot.cogs

unkempt canyonBOT
lofty mulch
#

My code doesn't produce any output, is there something wrong with it?

waxen granite
#
        coglist = self.bot.cogs
        for cog in coglist:
            cog = self.bot.get_cog(cogname.lower())```
gives a nonetype error for cog
hasty iron
#

it returns a mapping not a list

#

a mapping of str and Cog

#

meaning if you do for name, cog in self.bot.cogs.items() name will be a string and cog will be a Cog object

lyric moat
#

how do i do buttons command?

lofty mulch
hasty iron
#

even the first print?

lofty mulch
#

Nope, not even the first print

hasty iron
#

then the error is coming from Cogs.DryFile

lofty mulch
#

How could I fix it?

hasty iron
#

i don’t know what error you get

lofty mulch
#

It doesn't show any error from the terminal

hasty iron
#

it just doesn’t work?

lofty mulch
#

Actually, let me run it again

#

Nope, it just doesn't work

lyric moat
#

how do i do buttons command?

hasty iron
#

does the bot run?

lofty mulch
#

It gets online, but doesn't recognize any commands

#

Actually, it doesn't even report errors