#discord-bots

1 messages · Page 511 of 1

rigid island
#

see i take the code from here

stark hearth
#

how can i remove my bot from a server, but i am not owner of the server

pliant gulch
#

!d discord.Guild.leave

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
stark hearth
#

ok ty

lofty heron
#

hi, how can i get a member's account creation date with id?

@commands.command()
    async def tost(ctx, * args, time):
      age = datetime.utcnow() - #member's account creation date
      await ctx.send(age)
visual island
#

!d discord.Member.created_at

unkempt canyonBOT
#

property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.created_at "discord.User.created_at")
lofty heron
#

alright thanks

stark hearth
#
    @commands.command(aliases=["whois"])
    async def userinfo(self, ctx, member: discord.Member = None):

        if member == None:
            member = ctx.author

        roles = [role for role in member.roles][1:]

        embed = discord.Embed(
            description = f'**User Infomation - **{member.mention}',
            colour=member.color, 
            timestamp=ctx.message.created_at
            )

        embed.set_thumbnail(url = member.avatar_url)
        embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)

        embed.add_field(name='ID:', value=f'`{member.id}`')
        embed.add_field(name='Nickname:', value=member.display_name)

        embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
        embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))

        embed.add_field(name=f'Roles ({len(roles)})', value="\n".join([role.mention for role in roles]))
        embed.add_field(name='Top Role:', value=member.top_role.mention)

        embed.add_field(name = 'Bot:', value = member.bot)

        await ctx.send(embed=embed)

i want to change the time from utc to ptc

#

how would i do that

slate swan
#

Error:Ignoring exception in on_raw_reaction_remove Traceback (most recent call last): File "C:\Users\denis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 312, in _run_event await coro(*args, **kwargs) File "C:\Users\denis\OneDrive\Desktop\Developement\Discord Bot\cogs\reaktions-rollen.py", line 53, in on_raw_reaction_remove if role is not None: UnboundLocalError: local variable 'role' referenced before assignment

#

Code:```py
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 876220796081684541:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.client.guilds)

        if payload.emoji.name == ':mailbox_with_no_mail:':
            role = discord.utils.get(guild.roles, name='「Ping » News」')

        if role is not None:
            member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
            if member is not None:
                await member.remove_roles(role)
                print("done")
            else:
                print("Member not found.")
        else:
            print("Role not found.")```
#

because did you set the variable 'role' to if payload.emoji.name == ': mailbox_with_no_mail:': and called it to if role is not None:

#
    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        message_id = payload.message_id
        if message_id == 876220796081684541:
            guild_id = payload.guild_id
            guild = discord.utils.find(lambda g : g.id == guild_id, self.client.guilds)
            role = discord.utils.get(guild.roles, name='「Ping » News」')

            if payload.emoji.name == ':mailbox_with_no_mail:':
                if role:
                    member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
                    if member:
                        await member.remove_roles(role)
                        print("done")
                    else:
                        print("Member not found.")
            else:
                print("Role not found.")
#

you can try something like that

#

if you see we have define the role before "if statements"

slate swan
slate swan
#

you can try this way role = guild.get_role(role id)

#

And here you can check if user have the role

#
if member:
    if role in member.roles:
        await member.remove_roles(role)
#

I do not want to confuse you with all this, it is just better to write them correctly and with the right bases.

#

url="attachment://name.png"

#

!local-file

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

slate swan
#

@visual island cant understand sry.

visual island
slate swan
#

There are several called "kyle" previous wrote a problem I read it and deleted it. I wanted to answer him but I probably made the wrong mention. Excuse me.

heavy gull
#

How do I get the response message of a command to be eliminated in a certain time?

pallid meadow
#

and that will then delete the message after 5 seconds

heavy gull
#

thanks

covert igloo
#

whats the line to get guild's profile url

pallid meadow
covert igloo
#

the guilds icon

#

is it just discord.Guild.icon_url

pallid meadow
#

yeah but you have to call that on a guild object

covert igloo
#

yea got it ty

pliant gulch
#

Its not just accessing icon_url

#

As it isn't a link, rather an Asset object

#

you can cast str on it to get the CDN url

covert igloo
#

nah i jhust used it as an icon

slate swan
#
@client.command()
async def memberstat(ctx):
    for member in ctx.guild.members:
        try:
            print(f"{member.name}")
            userAvatarUrl = member.avatar_url
            print(userAvatarUrl)

why does this only get the avatar of 1 person

#

instead of every member

#

Im make discord bot "마시(masi)"

#

OMG

#

🤦‍♂️

slate swan
slate swan
#

Hmmmmmmm...

#

Im dont py code study....

#

걍 돼는데로하는뎅..

#

Zzz

#

I don't know what

#

Omg

slate phoenix
#

!ytdl

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)
fading harness
#

hi

#

how can i appeal a ban from discordpy

heavy gull
#

How do I make the bot send emojis?

fading harness
#

like

heavy gull
#

ok

fading harness
slate swan
#

i dont think you can do those things with a bot

fading harness
#

i tried it

slate swan
#

how can i make my bot reply to a message that triggers an action? for example, if i were to type {prefix}command, it would react to that message with an emoji, i was thinking ctx.author.message.add_reaction(emoji) but that didnt work, any ideas?

valid perch
#

ctx.message

#

Why would an member have a related message?

waxen granite
#
        guild = str(ctx.guild.id)
        try:
            gcid = self.giveawaychan[guild]
            oldgiveawaymsgid = self.giveawaychan[guild]["giveawaymessageid"]
            oldgiveawaychannelid = self.giveawaychan[guild]["giveawaychannelid"]
            oldgiveawaytime = self.giveawaychan[guild]["time"]
        except KeyError:
            gcid = {}
            oldgiveawaychannelid = {}
            oldgiveawaymsgid = {}
            oldgiveawaytime = {}
        ogchannel = self.bot.get_channel(oldgiveawaychannelid)
        ogmsg = await ogchannel.fetch_message(oldgiveawaymsgid)
        currenttime = datetime.datetime.utcnow()
        ogtime = ogmsg.created_at + datetime.timedelta(seconds = oldgiveawaytime)
        print(ogtime-currenttime)
        if ogtime > currenttime:```
for line `ogchannel = self.bot.get_channel(oldgiveawaychannelid)` it raises an error `TypeError: unhashable type: 'dict'`
covert igloo
#

how am i able to fix this

#

nvm got it

keen talon
#

Forgot or u don't know pithink

crystal wind
#

Does it apply if the bot plays music from your own system (your own files), and is not affiliated to youtube by any means?

#

Therefore, this applies to youtube most likely, with youtube_dl. I don’t know about Soundcloud or Spotify but that’s not a great idea either.

void abyss
#

can we still use discord.py to make own bot?

crystal wind
#

of course.

#

I use it.

void abyss
#

Ahh ic

crystal wind
#

People made extensions for it.

void abyss
#

idk i saw smth like disord.py shut down or smth

#

that's why

crystal wind
#

The creator of it said he won’t support it anymore, but made it open source I think.

void abyss
#

ahh ic

#

like no more updates coming up

crystal wind
#

But it’s far from being dead.

void abyss
#

anymore?

crystal wind
#

The community makes extensions of it

void abyss
#

so we use the extensions

crystal wind
void abyss
crystal wind
#

It was always

crystal wind
#

discord_components is such a good one for buttons

void abyss
#

ahh ic

#

also

#

one thing

crystal wind
#

hi

void abyss
#

We hv to include slash cmds?

crystal wind
#

But some extensions are including them.

#

I think it’s called discord-slash

boreal ravine
void abyss
#

Ahh ic

crystal wind
dapper cobalt
#

GitHub forks.

boreal ravine
crystal wind
#

oooh

void abyss
#

alts

dapper cobalt
#

!pypi disnake is a fork of dpy.

unkempt canyonBOT
boreal ravine
void abyss
#

ye

void abyss
#

ye seems like it

grand anvil
#

oh sed I was hoping to get components and slash commands in discord.py itself

void abyss
#

ye

dapper cobalt
#

Disnake has that.

crystal wind
dapper cobalt
#

You can use extensions as well.

grand anvil
crystal wind
#

Which one is the best for slash and buttons though? I never found one that takes everything

grand anvil
#

always better to have everything at one place

dapper cobalt
#

!pypi dislash.py is great for interactions and components.

unkempt canyonBOT
crystal wind
#

Thanks!

grand anvil
#

but with extensions diff. people can be using diff. extensions. Having them in discord.py will standardize it

dapper cobalt
#

Most of the forks are the exact same syntax as dpy, just with a different name.

grand anvil
#

true but still...

crystal wind
#

If we use multiple forks at the same time, does it affect the functions you call? Does it execute the command twice for example?

dapper cobalt
#

Well, most forks support slash commands, buttons and application commands.

crystal wind
#

O wait, you need to call them.

dapper cobalt
#

Though, I highly promote disnake. It's really great and stable.

crystal wind
#

I’ll try it out.

tropic briar
#

@hard trail Sorry bro for the late Reply Actually I went outside my home because of some work

#

I don't why it's not working

crystal wind
#

Oh yeah speaking of interactions, can buttons have custom colors or there’s only 4? (Blue, red, green and grey)

crystal wind
#

That’s very unfortunate.

crystal wind
#

ooof

#

a real need hm...

#

That’s quite unfortunate

dapper cobalt
#

Basically what they want is 1,000 people to spam their server asking for it. (I'm kidding)

crystal wind
#

I thought of doing a minigames with buttons, but now I think about it, I don’t think you can restrict the button to others (like permission) so this might be difficult.

dapper cobalt
#

You can add checks.

#

Check who clicked the button.

crystal wind
#

That’s from the buttons feature or you meant checking manually in code?

covert igloo
#

@dapper cobalt hey

#

im getting this error and i cant figure our why

dapper cobalt
covert igloo
dapper cobalt
covert igloo
#

client

dapper cobalt
#

Is that your commands.Bot instance?

crystal wind
#

You gotta define your check

#

Maybe

covert igloo
crystal wind
covert igloo
dapper cobalt
#

Is that inside a cog?

covert igloo
#

yes

dapper cobalt
#

await **self.**Bot.wait_for()

covert igloo
dapper cobalt
#

No problem.

crystal wind
#

By the way Scoopy

dapper cobalt
#

Yes?

waxen granite
#
    async def giveaway(self, ctx):
        guild = str(ctx.guild.id)
        try:
            gcid = self.giveawaychan[guild]
        except KeyError:
            gcid = {}
            if not gcid:
                # do something               
            else:
                print("else")
                try:
                    gcid = self.giveawaychan[guild]
                    oldgiveawaymsgid = self.giveawaychan[guild]["giveawaymessageid"]
                    oldgiveawaychannelid = self.giveawaychan[guild]["giveawaychannelid"]
                    oldgiveawaytime = self.giveawaychan[guild]["time"]
                except KeyError:
                    gcid = {}```
the else isnt getting triggered
dapper cobalt
# covert igloo

Could you please DM me the theme's name and the font family you use? I really love them.

crystal wind
#

Are we allowed to ask questions concerning ffmpeg for a bot if it’s not affiliated with youtube by any means?

dapper cobalt
#

Nope.

#

!ytdl

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)
crystal wind
#

Like playing mp3 files from local

#

Is this allowed?

dapper cobalt
#

If the songs are from YouTube then no.

crystal wind
#

I didn’t get them from youtube at all

#

I got them from that website where you can download sound effects

dapper cobalt
dapper cobalt
keen talon
crystal wind
#

okok I might ask my question later cause it’s very late rn xd

#

Thanks a lot!

dapper cobalt
#

But unfortunately, I cannot help you since I'm not familiar with Ffmpeg.

dapper cobalt
crystal wind
#

Let’s hope someone is familiar with it.

slate swan
#

.

keen talon
upbeat gust
#
    async def getavatar(ctx, member: discord.Member = None):
            if not member:
                member = ctx.message.author
            avatarURL = member.avatar_url
            return avatarURL```
```py
avatarURL = member.avatar_url
AttributeError: 'Context' object has no attribute 'avatar_url'```
does anyone know what i did wrong here
elfin island
#

show how you're calling the function

crystal wind
dapper cobalt
#

ctx.author will work as well.

waxen granite
#

how do i hyperlink text?

dapper cobalt
#

[text](url)

upbeat gust
# elfin island show how you're calling the function
@commands.command(name = 'ship', aliases = [])
async def ship(ctx, user1: discord.Member = None, user2: discord.Member = None):
  user1avatar = await myclass.getavatar(ctx, user1)
  user2avatar = await myclass.getavatar(ctx, user2)
vagrant brook
#

Class functions need self as the first parameter

#

Make sure you saved your file

waxen granite
# dapper cobalt `[text](url)`

await ctx.send(f"***There is already an active giveaway.\nYou can only create a new giveaway when the current active giveaway ends.\n[Current Giveaway](oldgiveawaymessageid.url) ends in {timeLeft}***" like that?oldgiveawaymessageid is a message

vagrant brook
#

Hyperlinks only work in embed descriptions

dapper cobalt
vagrant brook
#

I mean that counts as description too

#

:)

inland venture
#

@dapper cobalt u know how to set status for my discord bot?

#

im using pycharm btw

dapper cobalt
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter.
waxen granite
dapper cobalt
#

Is this a field value or an embed description?

waxen granite
#

just a msg

#

not embed

waxen granite
#

hyperlink dont work in normal msgs?

dapper cobalt
#

Not in python, no.

waxen granite
#

sad

dapper cobalt
#

I think it does in djs.

waxen granite
#

ye it does

vagrant brook
#

Oh I never knew it was possible to hyperlink in a normal message

upbeat gust
solemn grove
#
@bot.command(aliases=['em'])
async def create_embed(ctx):
    def check(message):
        return message.author == ctx.author and message.channel == ctx.channel
    
    try:
        await ctx.send('Waiting for a title')
        title = await bot.wait_for('message', timeout=30.0, check=check)
    except:
        await ctx.channel.purge(limit=2)
        await ctx.send('Timeout', delete_after=5)
    

    try: 
        await ctx.send('Waiting for a description')
        desc = await bot.wait_for('message', timeout=30.0, check=check)
    except:
        await ctx.channel.purge(limit=4)
        await ctx.send('Timeout', delete_after=5)

    embed = discord.Embed(title=title.content, description=desc.content, color=0x72d345)
    await ctx.send(embed=embed) 

How can I stop it to ask for description if the title isn't given?

vagrant brook
inland venture
#

its not showing up

dapper cobalt
#

Where do you have it?

upbeat gust
waxen granite
dapper cobalt
#

Certainly.

vagrant brook
#

That's not the right way to call class functions

#

You can just ignore the self part

#

So, self.get_avatar(ctx, ...)

upbeat gust
#

oh

covert igloo
#

@dapper cobalt is there a reason to why a command can't run if it's using a .json

upbeat gust
waxen granite
covert igloo
#

I have a data file and it works fine when I use the path to that file on my computer but once I push it out to github, the command doesn't function

waxen granite
#

how?

vagrant brook
dapper cobalt
waxen granite
# dapper cobalt You can.

embed = discord.Embed(description = f"***There is already an active giveaway.\nYou can only create a new giveaway when the current active giveaway ends.\n[Current Giveaway]{(ogmsg.jump_url)} ends in {timeLeft}***") this doesnt hyperlink the [Current Giveaway]

dapper cobalt
dapper cobalt
vagrant brook
covert igloo
#

Heroku

waxen granite
covert igloo
#

Using my repository on github

dapper cobalt
#

Well, I don't think the path of the file on heroku is same as it is on your computer.

vagrant brook
#

You swapped the brackets and the curly ones

dapper cobalt
covert igloo
#

I changed the name to just "data.json" instead of my computer path

#

It still doesn't work

dapper cobalt
waxen granite
dapper cobalt
waxen granite
dapper cobalt
#

No problem.

covert igloo
#

Under my cogs folder

dapper cobalt
#

Try cogs/data.json.

covert igloo
#

Ok will do

solemn grove
#

How to delete the trigger of the command?

upbeat gust
#

i think

upbeat gust
# vagrant brook So, self.get_avatar(ctx, ...)

im still not really sure how to fix it
i tried adding self to it but it still showed as 'self' is not defined
the same error as before came up when i moved the function out of the class

dapper cobalt
upbeat gust
dapper cobalt
#

Do you have

def __init__(self, bot): self.bot = bot

Under the class?

slate swan
#

Hi, Im new to python

solemn grove
boreal ravine
#

delay for what?

solemn grove
#

deleting the trigger

boreal ravine
#

u could use asyncio.sleep

waxen granite
#

Delay =

boreal ravine
#

its a coro though so dont forget to await it

dapper cobalt
#

!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.
dapper cobalt
amber imp
#

    @commands.command()
    @commands.has_role("giveaway")
    @commands.has_permissions(administrator=True)
    async def gstart(self, ctx, mins: int, prize):
        embed = discord.Embed(title="🎉 GIVEAWAY🎉", description=f"{prize}", color=discord.Color.random())

        end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
        embed.add_field(name="Ends at:", value=f"{end}UTC")
        embed.set_footer(text=f"Ends {mins} minutes from now")
        my_msg = await ctx.send(embed=embed)

        await my_msg.add_reaction("🎉")

        await asyncio.sleep(mins)

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

        users = await new_msg.users().flatten()
        # users is now a list of User...
        winner = random.choice(users)
        await ctx.send(f"congratulations! {winner.mention} won {prize}")
```help please
#
discord.ext.commands.errors.CommandNotFound: Command "gcreate" is not found
Ignoring exception in command gstart:
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\bots\studybot\cogs\events.py", line 29, in gstart
    users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'

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

Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\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: AttributeError: 'ComponentMessage' object has no attribute 'users'
boreal ravine
amber imp
green jacinth
#

help

amber imp
boreal ravine
green jacinth
#

please see that carrot channel or so

boreal ravine
green jacinth
#

@tropic briar that channel got hidden for me :(( cooldown huh

green jacinth
tropic briar
#

Hmm

boreal ravine
#

It means you used tabs/spaces in a bad way

amber imp
#

yes

boreal ravine
green jacinth
#
  async def kick(self, ctx, member: discord.Member, reason="No Reason"):
        if member == None:
            embed = discord.Embed(f"{ctx.message.author}, Please enter a valid user!")
            await ctx.reply(embed=embed)```
green jacinth
boreal ravine
#

Un-indent the command then re-indent it

green jacinth
#

done i did back space and then enter it fixed

green jacinth
boreal ravine
boreal ravine
amber imp
#

ok

green jacinth
boreal ravine
green jacinth
boreal ravine
green jacinth
boreal ravine
amber imp
#
        new_msg = await ctx.channel.fetch_message(my_msg.id)

        users = await discord.reaction.flatten()
        winner = random.choice(users)
        await ctx.send(f"congratulations! {winner.mention} won {prize}")
amber imp
#

im bit confused

ember mauve
#

is Discord.py rewrite better than the other one?
Many people use the other one

#

also

tranquil quest
#

How do I remove a reaction with the following info:

message ID
reactor ID
name/unicode of emoji

#

discord.p

green jacinth
#
      else:
            guild = ctx.guild
            embed = discord.Embed(title="Kicked!", description=f"{member.mention} has been kicked!!", colour=discord.Colour.blue(), timestamp=datetime.datetime.utcnow())
            embed.add_field(name="Reason: ", value=reason, inline=False)
            await ctx.reply(embed=embed)
            await guild.kick(user=member)```
ember mauve
amber imp
#

im confused can anyone help me plsssss

solemn grove
#

Why the bot isnt responding?

#
@bot.group(invoke_without_command=True)
async def help(ctx ):
  em= discord.Embed(
    title= "Help", 
    description="Use +help <command> for extended information on a command.",
    color=0xFFFFFF
  )
  em.add_field(name = "Moderation", value = "Will be added soon.")
  em.add_field(name = "**Embed**", value = "Creates embed.")
  em.add_field(name = "**Music**", value = "Will be added soon.")


  
  await ctx.send(f"{ctx.author.mention}", embed= em)
solemn grove
#

nope

#

it isnt responding on any cmd

amber imp
boreal ravine
solemn grove
amber imp
solemn grove
amber imp
solemn grove
#

just responding on events

tranquil quest
#

How do I remove a reaction with the following info:

message ID
reactor ID
name/unicode of emoji

boreal ravine
amber imp
solemn grove
#

yep

amber imp
#
@bot.group(invoke_without_command=True)
async def helpi(ctx):
    em = discord.Embed(
        title="Help",
        description="Use +help <command> for extended information on a command.",
        color=0xFFFFFF
    )
    em.add_field(name="Moderation", value="Will be added soon.")
    em.add_field(name="**Embed**", value="Creates embed.")
    em.add_field(name="**Music**", value="Will be added soon.")

    await ctx.send(f"{ctx.author.mention}", embed=em)
```this works fine
solemn grove
#

any command isnt working

boreal ravine
#

it worked fine-

tranquil quest
solemn grove
#

did i messed up anything here?

bot = commands.Bot(command_prefix= '+' , intents=intents, activity=activity, status=discord.Status.online)

boreal ravine
#

did u do bot.remove_command("help")

solemn grove
#

yes

boreal ravine
#

hm

upbeat otter
#

Guys, how do i get the role id here?

@client.command()
async def customrole(ctx, rolename: discord.Role=None, hexcode: discord.Color=None):
  if ctx.message.channel.id == 893572364858699796:
    if hexcode is None:
      await ctx.send("Enter a hexcode!")
      return
    if rolename is None:
      await ctx.send("Enter the role name!")
      return
    await open_account(ctx.message.author)
    await open_account2(ctx.message.author)
    with open("roles.json", "r") as f:
      users = json.load(f)
    user = ctx.message.author
    if users[str(user.id)]["roles"] == 1:
      await ctx.channel.purge(limit=1)
      await ctx.send("You have reached the rate limit of custom roles!", delete_after=5)
      return
    member = ctx.message.author
    await ctx.guild.create_role(name=rolename, color=hexcode, permissions=discord.Permissions(read_messages=False))
    await ctx.channel.purge(limit=1)
    role = discord.utils.get(ctx.guild.roles, name=rolename)
    await member.add_roles(role)
    await role.edit(position=60)
    await ctx.send(f"Successfully created {rolename} role for you!", delete_after=5)
    with open("roles.json", "r") as f:
      users = json.load(f)
    users[str(user.id)]["roles"] += 1
    with open("roles.json", "w") as f:
      json.dump(users, f)
    with open("botrole.json", "r") as f:
      roleid = json.load(f)
    role2 = discord.utils.get(ctx.guild.roles, id=rolename.id)
    print(role2)
    print(type(role2))
    roleid[str(ctx.message.author.id)]["roleid"] += role2
    with open("botrole.json", "w") as f:
      json.dump(roleid, f)
amber imp
unkempt canyonBOT
#

Hey @solemn grove!

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

upbeat otter
boreal ravine
amber imp
#

okk

#

but

boreal ravine
amber imp
#

i not got my question answer

upbeat otter
solemn grove
upbeat otter
#

It creates a role for the user and i want to get the id of that role

boreal ravine
#

o

solemn grove
#

checkout my code

upbeat otter
solemn grove
solemn grove
upbeat otter
upbeat otter
amber imp
#
import discord
from discord.ext import commands
import asyncio
import datetime
import random


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

    @commands.command()
    @commands.has_role("giveaway")
    @commands.has_permissions(administrator=True)
    async def gstart(self, ctx, mins: int, prize):
        embed = discord.Embed(title=":tada: GIVEAWAY:tada:", description=f"{prize}", color=discord.Color.random())

        end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
        embed.add_field(name="Ends at:", value=f"{end}UTC")
        embed.set_footer(text=f"Ends {mins} minutes from now")
        my_msg = await ctx.send(embed=embed)

        await my_msg.add_reaction(":tada:")

        await asyncio.sleep(mins)

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

        users = await new_msg.users().flatten()
        # users is now a list of User...
        winner = random.choice(users)
        await ctx.send(f"congratulations! {winner.mention} won {prize}")

def setup(bot):
    bot.add_cog(events(bot))
#

can anyone help me

upbeat otter
#

whats the error?

amber imp
#
C:\bots\studybot\venv\Scripts\python.exe C:/bots/studybot/main.py
bot is ready
Ignoring exception in command gstart:
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\bots\studybot\cogs\events.py", line 29, in gstart
    users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'

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

Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39\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: AttributeError: 'ComponentMessage' object has no attribute 'users'
solemn grove
#
@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
        await message.channel.send(embed=embed)

I just removed this and the bot works perfectly
Why is it so?

solemn grove
#

How to fix that?

amber imp
spring flax
#

or change the decorator from @bot.event to @bot.listen()

spring flax
solemn grove
#
@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
        await message.channel.send(embed=embed)
        await bot.process_commands(message)
amber imp
#
import discord
from discord.ext import commands
import asyncio
import datetime
import random


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

    @commands.command()
    @commands.has_role("giveaway")
    @commands.has_permissions(administrator=True)
    async def gstart(self, ctx, mins: int, prize):
        embed = discord.Embed(title="🎉 GIVEAWAY🎉", description=f"{prize}", color=discord.Color.random())

        end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins)
        embed.add_field(name="Ends at:", value=f"{end}UTC")
        embed.set_footer(text=f"Ends {mins} minutes from now")
        my_msg = await ctx.send(embed=embed)

        await my_msg.add_reaction("🎉")

        await asyncio.sleep(mins)

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

        users = await reaction.users().flatten()
        # users is now a list of User...
        winner = random.choice(users)
        await ctx.send(f"congratulations! {winner.mention} won {prize}")

    

def setup(bot):
    bot.add_cog(events(bot))
```help pls
#

C:\bots\studybot\venv\Scripts\python.exe C:/bots/studybot/main.py
bot is ready
Ignoring exception in command gstart:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bots\studybot\cogs\events.py", line 29, in gstart
users = await new_msg.users().flatten()
AttributeError: 'ComponentMessage' object has no attribute 'users'

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

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

Process finished with exit code -1

mellow merlin
#

How hard is it to make a bot to remove a role simultaneously with another?

For example, to make members automatically lose a role when they lose the server booster role?

spring flax
#

What's wrong with it

slate swan
#

i dont under stand.........

#

omg

#

왜저거 cc cv하면 오류나는거지

#

ㅠ.ㅠ

solemn grove
spring flax
slate swan
timber crescent
#

I'm tryna take two consecutive messages as a second input

#

But the second part does trigger

#

Lemme show what I'm tryna do just a sec

#
async def on_message(message):
    if message.author==client.user:
        return
    if message.content.startswith('BB'):
        if message.content==('BB test'):
            await message.channel.send('you have requested a test session, are you sure you wish to proceed')
            async def on_message(cons_message):
                if cons_message.content==('yes'):
                    await cons_message.channel.send('you have just confirmed that you requested a test session are you sure regarding your current course of action?')
solemn grove
#
@bot.listen()
async def on_message(message):
    if bot.user.mentioned_in(message):
        embed = discord.Embed(title='**Close Combat Esports®**', description = '**My prefix is `+`\nYou can type `+help` for more info.**', color=0xFFFFFF)
        await message.channel.send(embed=embed) 
#

@spring flax

timber crescent
#

what'd be the right way to do this?

#

like two consecutive command thingies but the second one only triggers if the first one was used....first

tropic briar
#
@client.command()
@client.has_permissions(ban_members = True, kick_members = True) 
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` Why the permission thing is not working
slate swan
#

welp, how can i make a command such that if it is not allowed by mods it cant be used

boreal ravine
unkempt canyonBOT
#

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

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

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

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

hmm

solemn grove
tropic briar
#

i think this doesn't works

boreal ravine
#

You did client.has_permissions

tropic briar
#

Lemme try and see if it works

tropic briar
boreal ravine
#

yes

#

hm

tropic briar
#
@client.command()
@discord.ext.commands.has_permissions(ban_members = True)
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` Everything looks alright
boreal ravine
#

thats the extension

tropic briar
#

You said

#

Idk what we use for members

boreal ravine
#

check the gist

tropic briar
#
@client.command()
@commands.has_role("Mod") 
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` but the command part?
#

like I don't think it should be commands

slate swan
#

It's correct, commands is how it's supposed to be

steep estuary
#

how to check if a user have a role in if else?

slate swan
tawdry perch
#
if roleobj in member.roles
slate swan
tawdry perch
#

Depends what you want

slate swan
#

Or ```py
if "some_role_name" in (role.name for role in member.roles):
pass

steep estuary
tranquil quest
#

how do I remove a reaction w/ a RawReactionActionEvent

steep estuary
tranquil quest
#

you can use .remove on a reaction, but not a raw reaction

slate swan
tranquil quest
#

how

#

I tried something like that but got so many errors and it was so long

slate swan
slate swan
tropic briar
# boreal ravine check the gist
@client.command()
@commands.has_role("Mod") 
@commands.has_role("Admin") 
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
``` So this is what I have now but it works when I have the admin role but it doesn't even when I have Mod role
#

So it works when I have Admin but now when I have Mod

tranquil quest
slate swan
#

That would most likely raise you an error

#

Define each thing in a variable of its own

slate swan
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
tropic briar
#

so How should I put role names in that parenthesis

slate swan
#

Like how you've done it before

tropic briar
#

ok

tranquil quest
#
AttributeError: 'TextChannel' object has no attribute 'get_message'
#

i thought it did

slate swan
#

Fetch it

tranquil quest
#

alr

slate swan
#

.get_ methods only work for the bot because they use the bot's cache

tranquil quest
#
                channel_class = await bot.get_channel(reaction.channel_id)
                message_class = await channel_class.fetch_message(reaction.message_id)
                await message_class.remove_reaction(reaction.member, reaction.emoji.name)
#

TypeError: object TextChannel can't be used in 'await' expression

#

ill try remove the await

slate swan
#

you dont have to await get_x methods

#

^

tranquil quest
#

oh

slate swan
#

Emoji is first, member second

tranquil quest
#

wrong way around

#

i just need to fix the sql part

slate swan
tranquil quest
#

yeah ik

tropic briar
#
@client.command()
@commands.has_any_role("Admin", "mod", "Owner")
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)
``` Why is this not working even when I have the Mod and Admin role
lament mesa
#

Typehint amount with int

tropic briar
#

hmm

#

where

#

it works when I remove The permission check

slate swan
#

@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx,amount : int):
await ctx.channel.purge(limit = amount)

tropic briar
#

yes

slate swan
tropic briar
#

ok

slate swan
slate swan
tropic briar
#

oh yeh

slate swan
#

XD

tropic briar
#

lemme try now

slate swan
slate swan
# tropic briar lemme try now

@clear.error
async def clear_error(ctx, error):
if isinstance(error,commands.MissingRequiredArgument):
await ctx.send('Please specify the amount of message to delete')

#

error handling

tropic briar
#

alright it's working

slate swan
#

i knew itlol

tropic briar
#
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)
#

So do you also know How are music bots made ?

slate swan
tropic briar
#

huh? why

#

We cannot make Music bots?

visual island
#

!ytdl

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)
tropic briar
#

So How can I make a music bot then

slate swan
slate swan
tropic briar
#

So you are saying that We cannot make music bots

#

then what will you help me in

slate swan
#

accept frnd req

#

i will provide everything

mellow merlin
#

someone pls help 😄 I need the code to remove a role once another is removed

#

please ❤️

atomic topaz
#

is there any way to get the channel id with channel name?

slate swan
#

I gave u the idea you do the code yourself

slate swan
unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
slate swan
#

why

#

?

#

oh wait nvm

#

I thought he had the id

#

what a missunderstanding

#

It's alr

atomic topaz
# slate swan !d discord.utils.get
guild = ctx.message.guild
  channel_name = str(ctx.message.author).split("#")[0] + "-bots"
  channel_list = ([i.name for i in guild.channels])
  channel = discord.utils.get(ctx.guild.channels, name=channel_name)
  channel_id = channel.id
#

look i did this

#

but that's returning none

#

but that channel exists

#

and the name is correct too

slate swan
#

Try printing everything

atomic topaz
#

alright

gusty gorge
#

i have 2 async commands and i can only use 1 if i delete i also have 1 prefix which is a . how do i make it so i canuse 2 for both commands

atomic topaz
slate swan
#

You're using str(ctx.message.author)

#

To define the channel name

slate swan
#

Since it's a command make it take the channel param

gusty gorge
slate swan
#

send the code

#

^

gusty gorge
#

i dont got but its for all ocdes

slate swan
#

If u don't got the code we can't help u

#

wat

#

We have no way of knowing what's causing the error without having any example/proof to look at

atomic topaz
slate swan
slate swan
#

Then use it on the channel

atomic topaz
#

alright

slate swan
#

Actually wait that will return the TextChannel object that ur looking for already

#

So u don't have to use utils to get it anymore

slate swan
#

What do u want this command to do

#

but that would return any textchannel they type in

gusty gorge
atomic topaz
slate swan
#

even if it's not the needed one

slate swan
#

channel_name = str(ctx.message.author).split("#")[0] + "-bots" makes me think we're looking for a very specific channel

atomic topaz
#

but that's not the point

slate swan
#

(replace str(ctx.author) with ctx.author.name)

slate swan
atomic topaz
slate swan
#

^

somber tree
#

Im finally back

#

the server that tried to help me make a gdps with a discord bot

#

This time I want to link my discord bot to my mc aternos server

slate swan
#

what da

somber tree
#

I've seen it before

atomic topaz
#

how to get channel id by channel name?

valid perch
slate swan
somber tree
desert shell
valid perch
#

Ive got code to connect a python bot to mc server without anything server side

#

Monitors chat n such, two way. If thats your goal?

mellow merlin
#

please give me a line of code to remove a role once another is removed D:

somber tree
#

I don't need it to join my mc server

#

and plus I can't cuz I only have bedrock

valid perch
somber tree
#

my servers are usually survival ones

valid perch
#

Well either you connect with something, or use a server side plugin

tropic briar
#
@client.command()
async def topic(ctx):
  await ctx.send(random.choice(topic))
``` I am trying to do as the bot @lament depot do here
#

but it's not working like I want to get a random topic from a list called topic

solar pike
#

how to add an embed image

dapper cobalt
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/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
solar pike
#

👍

tropic briar
#

Everything looks neat and clean

dapper cobalt
tropic briar
#

I am putting

#

topic there so it should print a random topic

slate swan
#

oh sorry

solar pike
#

ah np

#

hehe ty

tropic briar
#

!e

import random
list = [1, 2]
print(random.choice(list))
dapper cobalt
tropic briar
#

You said it is thinking it's a function

solar pike
#

how to set color to embed

tropic briar
#

Can you tell me what should I do

slate swan
dapper cobalt
#

The first sentence.

tropic briar
#

So how to name it

dapper cobalt
#

Just add a"s".

tropic briar
#

where

hasty iron
#

you probably dont know enough python

#

when did you start coding in python

solar pike
#

amm how to set using a color code

dapper cobalt
tropic briar
keen comet
solar pike
tropic briar
#

I am new to bot dev

dapper cobalt
hasty iron
#

naming a variable isn’t exclusive to bot dev

somber tree
#

What is the coding for my discord bot to type?

#

It's been a long time so I dont remember

hasty iron
#

!d discord.ext.commands.Context.typing

unkempt canyonBOT
#

async with typing()```
Returns a context manager that allows you to type for an indefinite period of time.

This is useful for denoting long computations in your bot.

Note

This is both a regular context manager and an async context manager. This means that both `with` and `async with` work with this.

Example Usage...
somber tree
#

what now?

solar pike
#

amm error when i add img

somber tree
#

I dont remember this

slate swan
solar pike
#

reef shell
#

you didn't define any variable named 'embed'

#

that's why

slate swan
#
your_embed_name.set_image(url='image_link')
solar pike
#

OOO KKK GOTIT

somber tree
#

Now i need the coding that links my discord bot to aternos.

#

does anyone know the coding that links a discord bot to aternos?

unkempt canyonBOT
limber mountain
somber tree
#

This is the coding I have so far:

@bot.command(pass_context=True)
async def ping(ctx):
  channel = bot.get_channel(893773954332897290)
  await channel.send```
#

There's nothing after the send because I want it to send a message when my aternos mc server is online

mellow merlin
#

right. I will pay for someone to make me a simple bot.

#

DM me

somber tree
#

I'm just gonna give up

#

No one is helping me

limber mountain
slate swan
#

await channel.send("hello")

#

you always have to call the function, no matter what

#

and you can remove pass_context=True, since it does nothing

tropic briar
tropic briar
slate swan
#

what

#

no

tropic briar
#

Oh wait

#

No sorry

#

send("hey there")

slate swan
#

@somber tree

crystal cliff
#

@Bot.command()
AttributeError: 'Command' object has no attribute 'command'
 {why is this wrong, it was working great, last night 🤔}

slate swan
#

What do u have Bot defined as and where

#

Hey, some really weird bug appears to me

Code:

@bot.event
async def on_message(message):
  embed = Embed()
  channel = message.channel
  if channel == chan(message.guild,"suggestions"):
    await message.delete()
    embed.title = "Suggestion"
    embed.description = ''
    embed.add_field(name="from:", value=f"{message.author.name} ({message.author.id})", inline=False)
    embed.add_field(name="content", value=message.content, inline=False)
    await channel.send(embed=embed)

Problem:

I am basically trying to resend the message as an embed, so suggestions are more detailed / cannot be deleted. It is sending the embed!... But it deletes it right away

Error:

Invalid Form Body
In embed.fields.1.value: This field is required

I have added the value kwarg!!!

#

Btw chan() gets the channel object, I coded that one myself lol

crystal cliff
slate swan
slate swan
#

Meaning if the user uploads a file it won't work

#

I did not

#

Do u have intents

#

Yes

#

all()

dusk pumice
#

?

slate swan
#

Hmm then idk

dusk pumice
#

hello

slate swan
#

Really weird, right?

#

Hm

slate swan
sweet pilot
#

why does my bot fail to assign a role as soon as someone joins the server?

#

is it something with accepting the rules

sweet pilot
#

no error

slate swan
#

Code?

sweet pilot
#

everything works perfectly

#

it doesn't work perfectly

slate swan
#

Do u have that popup thing where people have to confirm something first before joining the server (some discord feature)

sweet pilot
slate swan
#

That could be the issue

sweet pilot
slate swan
#

I forgot what was its name in the lib tho

slate swan
#

Just forgot what it was called 😔

sweet pilot
#

wouldn've been better if I got an error

slate swan
#

Then it's bc of that

#

@slate swan

Theres a second where I am able to see the embed and it shows the message.content in value

#

Ah now I see the issue

#

Hm?

#

You're deleting and sending the message in the same channel

#

Meaning that even if the bot sends a message, it will also count

#

Huh am I?

#

Where

#

Add ```py
if message.author.bot:
return

#

OHHHH

#

HAHAHAHAHAHA

#

I get it yer

#

Thanks lets see if it works

#

Yw

#

Yey

umbral pollen
#

I’m sorry to interrupt anything if I do, since I started using uptimerobot, my bots start command stopped working and shows these errors

dusk pumice
#

Why doesn't my code work...

@tasks.loop(seconds=1)
async def bot_run_time():
  작동시간 = 0
  if datetime.datetime.now().minute % 5 == 0 and datetime.datetime.now().second == 0:
    a = time.strftime('%c', time.localtime(time.time()))
    day = datetime.datetime.now().date()
    try:
      while True:
        guilds = int(0)
        presence = int(0)
        for i in bot.guilds:
          작동시간 = 작동시간 + 5
          guilds = int(guilds + 1)
          botruntimeembed = Embed(title="a", description=f'a', color=0xfff700, timestamp='now')
          hook4.send(embed=botruntimeembed)
          await asyncio.sleep(300)
    except:
      hook4.send("a")
slate swan
dusk pumice
#

yes

#
bot_run_time.start()

I put this code in on_ready()

slate swan
slate swan
umbral pollen
dusk pumice
#

well I doesn't care for time

#

just working after 5min

slate swan
#

You forgot to put ctx somewhere in a command, read the error

dusk pumice
#

I just want an Notice bot

umbral pollen
slate swan
dusk pumice
#

How

dusk pumice
#

How do i fix this

#

ah

slate swan
#

@tasks.loop(minutes=5)

dusk pumice
#

I made an hook with dhook

hasty iron
#

whats that

dusk pumice
#

it's for discord hook

#

Webhook

slate swan
#

Dpy already has webhook support

dusk pumice
#

oh?

#

I did't know that

#

I'd like to join DPY server

dusk pumice
#

How do I work selenium in relp it?

hasty iron
dusk pumice
#

I mean how to connect with bot...

solar pike
#

how to separate all bot commands to different folder from main.py

hasty iron
#

use cogs

umbral pollen
#

Use cogs

solar pike
#

ooooooookk

umbral pollen
#

Yes!

boreal ravine
#

bruh

#

no spoonfeed

umbral pollen
#

How do I do an code block?

#

👍

boreal ravine
#

-_-

high flame
#

!code

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.

high flame
#

"in dms" ugh

#

we don't spoonfeed

#

code it yourself

keen comet
#

Yes

high flame
#

we can help but not giving all the code

#

learn python then discord.py, don't start with dpy first

boreal ravine
#

Whats the error?

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

keen comet
#

Stop pasting your bot token

slate swan
#

how do i make variables for custom emojis on discord.py?

boreal ravine
high flame
#

ignore it

#

or drag your cursor on it and see the issue

boreal ravine
#

it'll be "invalid synxtax"

high flame
#

that's valid syntax

slate swan
boreal ravine
#

it's invalid

slate swan
#

idk how to explain it very well

slate swan
slate swan
hasty iron
#

and use a class

slate swan
hasty iron
#

the class would load the json file and then set the attributes

heavy radish
#

I want to use multiple COGs/Folders. Can I still use this or do I need to change the last line?

@bot.event
async def on_ready():
  for cog in os.listdir(r"COGs"): 
      if cog.endswith(".py"):
          try:
              cog = f"COGs.{cog.replace('.py', '')}"
              bot.load_extension(cog) 
          except Exception as e:
              print(f"{cog} is failed to load:")
              raise e
  print(f"Logged in as {bot.user}")
boreal ravine
heavy radish
#

How about the login part

heavy radish
boreal ravine
#

use self?

heavy radish
#

ye

hasty iron
heavy radish
#

Ahh

#

What should I use?

boreal ravine
heavy radish
#

I want to have multiple folders

hasty iron
#

?

boreal ravine
heavy radish
#

Yeaaa, How?

boreal ravine
#

wym how

spring flax
#

you dont need an event for loading cogs

heavy radish
#

What should I do?

boreal ravine
heavy radish
#

Like I want to have multiple folders of COGs. That code wont work what should I use ?

boreal ravine
#

multiple cog folders?

slate swan
#

hey can someone help?

heavy radish
#

I want to name the folders like Commands, Rooms, Utilities

#

... and more

boreal ravine
heavy radish
#

I dont load other folders

slate swan
#

in an embed say if i want to use a custom emoji, i do description= 'hello world' how do i use a custom emoji because when i do description= 'config.tick hello' it dosent work

heavy radish
#

That's why I need help

boreal ravine
heavy radish
#

I only have that COGs folder

#

I want to now how many

boreal ravine
#

u said u wanted multiple cog folders?

heavy radish
#

the on_ready wont work if I duplicate it

#

Yes

boreal ravine
#

its just a matter of changing names

boreal ravine
# heavy radish the on_ready wont work if I duplicate it
for cog in os.listdir(r"COGs"): 
      if cog.endswith(".py"):
          try:
              cog = f"COGs.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"COGs_two"): 
      if cog.endswith(".py"):
          try:
              cog = f"COGs_two.{cog.replace('.py', '')}"
              bot.load_extension(cog) 
#

just put that in the on ready??

heavy radish
#

Wow

#

It was that simple...

boreal ravine
#

yeah

#

😐

spring flax
boreal ravine
hasty iron
#

it can be called twice

boreal ravine
hasty iron
#

what what

boreal ravine
#

that will raise an error if on_ready is called again

hasty iron
#

yea

#

it will

boreal ravine
#

u said it cant be called twice?

spring flax
#

why are you loading cogs on an event?

hasty iron
boreal ravine
hasty iron
#

i said it will raise an error if its called again

#

if its called again

boreal ravine
#

thats the same meaning innit

hasty iron
#

what

#

do you understand english

spring flax
boreal ravine
spring flax
#

it does matter. Do not load cogs on an on_event.

boreal ravine
#

?

hasty iron
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
spring flax
#

That was your code and what you said?

hasty iron
#

this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

boreal ravine
#

what code

#

just load the cogs else where?

#

stop making a big fuss out of small things lol

hasty iron
#

dude what

#

we just told you that on_ready can be called twice

#

and you misunderstood basic english

boreal ravine
#

I'm not american?

hasty iron
#

nor am i

spring flax
#

anyways

heavy radish
boreal ravine
#

do i really need to help you with that lol

heavy radish
#

Ye

boreal ravine
#

bruh

#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

heavy radish
#

It is what it is

left dove
#

so that we can find where ur indentation error starts

heavy radish
#
for cog in os.listdir(r"Admin"): 
      if cog.endswith(".py"):
          try:
              cog = f"Admin.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Embeds"):
      if cog.endswith(".py"):
          try:
              cog = f"Embeds.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"General"): 
      if cog.endswith(".py"):
          try:
              cog = f"General.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Misc"): 
      if cog.endswith(".py"):
          try:
              cog = f"Misc.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Room"): 
      if cog.endswith(".py"):
          try:
              cog = f"Room.{cog.replace('.py', '')}"
              bot.load_extension(cog)               
left dove
#

not this full

heavy radish
#

?

#
import discord
import os
from discord import member
from discord.ext import commands
from datetime import datetime
from keep_alive import keep_alive

bot = commands.Bot(command_prefix="??", activity=discord.Activity(name="The Timelines", type=discord.ActivityType.watching), help_command=None, case_insensitive=True)
bot.launch_time = datetime.utcnow()

for cog in os.listdir(r"Admin"): 
      if cog.endswith(".py"):
          try:
              cog = f"Admin.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Embeds"):
      if cog.endswith(".py"):
          try:
              cog = f"Embeds.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"General"): 
      if cog.endswith(".py"):
          try:
              cog = f"General.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Misc"): 
      if cog.endswith(".py"):
          try:
              cog = f"Misc.{cog.replace('.py', '')}"
              bot.load_extension(cog) 

for cog in os.listdir(r"Room"): 
      if cog.endswith(".py"):
          try:
              cog = f"Room.{cog.replace('.py', '')}"
              bot.load_extension(cog)               



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

This

cloud dawn
heavy radish
#

Hmmmm

#

So what do I do?

left dove
#

here down its correct but somewhere in top the indentation error exists

left dove
#

wait what

heavy radish
#

What's happening

fickle dust
#

!e
import maths
print (maths.pow(2,10))

slate swan
#

how do i use custom emojis inside an embed?

left dove
heavy radish
#

What do I do?

left dove
heavy radish
left dove
#

u cannot ping

#

lol

slate swan
#

ㅠㅠㅠㅠㅠㅠ

heavy radish
slate swan
cloud dawn
# heavy radish ```py import discord import os from discord import member from discord.ext impor...

here is a shorter one anyways ```py
import discord
import os
from discord import member
from discord.ext import commands
from datetime import datetime
from keep_alive import keep_alive

bot = commands.Bot(command_prefix="??", activity=discord.Activity(name="The Timelines", type=discord.ActivityType.watching), help_command=None, case_insensitive=True)
bot.launch_time = datetime.utcnow()

for f in [r"Admin", r"Embeds", r"General", r"Misc", r"Room"]:
for cog in os.listdir(f):
try:
cog = f"Admin.{cog.replace('.py', '')}"
bot.load_extension(cog)
except(Exception) as e:
print(e)

keep_alive()
bot.run(os.getenv('TOKEN'))

left dove
#
emoji=bot.get_emoji(emoji_id)
await ctx.send(f"{emoji}")
heavy radish
#

Ahh, Thank You!!

left dove
heavy radish
#

cog = f"Admin.{cog.replace('.py', '')}" Is this right?

slate swan
#
async def embed(ctx):
    embed = discord.Embed(
        title = 'test',
        description = 'config.tick test',
        color = config.color
    )

    embed.set_footer(text='testing')```
#

i cant use config.(emojiname) inside description

slate swan
left dove
#

first get the emoji id

slate swan
#

then

left dove
#

then

cloud dawn
visual island
#

[:-3]

left dove
#
@bot.command()
async def embed(ctx):
    emoji=bot.get_emoji(emoji_id)
    embed = discord.Embed(
        title = 'test',
        description = f'config.tick test {emoji} ',
        color = config.color
    )

    embed.set_footer(text='testing')
    await ctx.send(embed=embed)
cloud dawn
visual island
left dove
slate swan
signal canopy
#

does anyone know how can you recreate UnbelievaBoat's "suggest" command?, i don't know how is it able to send a message with user's avatar

left dove
#

@slate swan

slate swan
#

ohh ok

slate swan
# left dove in `emoji_id` put that `ID`
async def testembed(ctx):
    emoji=bot.get_emoji(893824092816441354)
    embed = discord.Embed(
        title = 'test',
        description = f'test {emoji} ',
        color = config.color
    )
#

? like that

boreal ravine
slate swan
# left dove yea

‎||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||https://khadz.fuckedyourmom.today/​‌‌‌‌​‌​​‌​​​​‌‌​‌‌‌​​‌​​​‌‌‌​​‌​‌‌​‌‌‌‌​‌‌​‌‌​​​​‌‌​‌​​​‌​​‌​​​

boreal ravine
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
signal canopy
#

like this:

signal canopy
slate swan
boreal ravine
unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
keen comet
left dove
#

not from other servers @slate swan

slate swan
signal canopy
left dove
#

hmm does the bot have access? @slate swan

slate swan
#

yep

boreal ravine
reef shell
left dove
#

can u use that emoji here @slate swan

slate swan
reef shell
#

ctx.channel.send or ctx.send

left dove
#

891768580994138153

#

id is this same which u entered?

#

@slate swan

signal canopy
slate swan
#

yup

boreal ravine