#discord-bots

1 messages · Page 470 of 1

valid niche
#

well....not working can be anything

#

tho the first issue i see glaring is naming

stark hearth
#

so a client.run i am assuming

valid niche
#

i wonder who in the world is suddenly tellling EVERYONE to do client = commands.Bot because i suddenly see EVERYONE coming here using wrong naming

stark hearth
valid niche
#

pep 8

#

if you don't follow good naming conventions now, god knows wherever you don't either

#

learn yourself the good habits of writing clear and easily maintainable code

valid niche
stark hearth
valid niche
lucid vale
#

How do you access the member ID of the user that used a slash command? The solutions i've found on stack overflow are just giving me the member ID of the bot's response to the slash command.

valid niche
valid niche
#

So discord_slash

lucid vale
#

ye

slate swan
#
<Message id=887099213148741712 channel=<TextChannel id=761025438986010665 name='new-joiners' position=21 nsfw=False news=False category_id=457657319564771338> type=<MessageType.new_member: 7> author=<User id=327491696692822016 name='asapglocky' discriminator='2238' bot=False> flags=<MessageFlags value=0>>```
#

what's the best way to take this text and extract just the member id from it

vale root
#

How do I make it so text is hyper linked to a url in a embed?

slate swan
#

[link text here](url here)

#

@vale root

valid niche
#

Sadly the module doesn’t have documentation so I had to dig into the source on GitHub

lucid vale
#

thats prob why i was so lost lol

#

tysm

valid niche
vale root
valid niche
#

You don’t take the values from that print

stark hearth
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.
valid niche
#

You just use the attribute

stark hearth
valid niche
vale root
valid niche
#

That’s one way yes, but the rest all uses text

vale root
#

wait

#

What if i just do

url = 'Pizza pizza'

then do {url}
in the description where i want it?

#

wait no

#

idk what i was just thinking

valid niche
vale root
#

?

valid niche
#

JavaScript jokes

vale root
#

:c

valid niche
vale root
#

lol

slate swan
#
async def on_ready():
    await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game('bot stuff'))```
#

it wont work

vale root
#

so how do i get the hyper link in the embed though cus i cant find anything

slate swan
#

u trynna make the bot post link on command?

valid niche
#

Do NOT make any discord api call in on ready. NEVER

slate swan
#

why?

vale root
#

damn

slate swan
#

whats wrong

#

im scared bro dont say it like that

vale root
#

lmao

valid niche
#

On ready fires before the client is ready and can lead to cache corruption if you make api calls. Also on ready can fire multiple times and can get you api banned

slate swan
#

OH DAMN

#

OH FUCK IM SCARED

#

fix the line for me pls

valid niche
#

Luckily there is a solution

vale root
#

:/

#

Make a command for that?

#

Easier and safer?

valid niche
#

Just pass activity to the commands.Bot constructor

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
vale root
#
@commands.command(name="setstatus")
    async def setstatus(self, ctx: commands.Context, *, text: str):
        await self.bot.change_presence(activity=discord.Game(name=text))
valid niche
#

See how it has an activity option in the docs? Use that

#

That is a safe way to set a status right as you come online

slate swan
#

bro i need to take a shit and u made my but cheecks close so hard i think im having a stroke

valid niche
#

Lmao

vale root
#

;/

vale root
#

Cus im lost

valid niche
slate swan
valid niche
#

What I said is like worst case scenario but it is possible

vale root
#

So add that where in this

 
@commands.command(name="ssuvote")
    async def ssuvote(self,ctx):
        embed = discord.Embed(title = f"Server Start Up Vote", description =f"Vote With the ✅ mark if you plan on attending." "\n" "\n" " Vote with a ❌ if you can not join." "\n""\n" "If you vote with the check you must join when ssu opens if not you will be warned!" "\n" "\n" "** If you get warned and join the Sesh then you can dm a admin to get it taken away!**")
        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')
        msg = await ctx.send(embed=embed) 
        await msg.add_reaction("✅")
        await msg.add_reaction("❌")
        await ctx.message.delete()
slate swan
#

class MyClient(discord.Client):
async def on_ready(self):
print('Ready too be used!') here is another one

vale root
#

I want it to become the title when i change the title

valid niche
#

It’s just in the string

vale root
#

So i want the title to change so i do

f"[Server start up vote]{pizza.cem}
?

valid niche
#

You forgot something

vale root
#

What

valid niche
vale root
#

oh yea () not {}

#

ight ima try that

slate swan
#

@valid niche can u check dms real quick lol

valid niche
#

Assuming pizza.cem is a link

valid niche
#

You’ll be silently ignored

slate swan
#

😦

#
from discord.ext import commands

#discord.Intents.all()
intents = discord.Intents.default()

client = commands.Bot(command_prefix='!', intents=intents)

@commands.command(name="Do.Not.Disturb")
    async def setstatus(self, ctx: commands.Context, *, text: str):
        await self.bot.change_presence(activity=discord.Game(name=text))

@client.command()
async def clear(ctx, ammount=10):
        await ctx.channel.purge(limit=ammount)

here was the api ban thingie can u add it?

    async def on_message(self, message):
        # don't respond to ourselves
        if message.author == self.user:
            return

        if message.content == 'you':
            await message.channel.send('Shalom, mf hows it hanging')

client = MyClient()
client.run('token')```
valid niche
#

!codd

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

can u add the api ban thingie can u fix it?

slate swan
#

ah forgot

valid niche
#

Not sure why it accepted the codd typo but sure

#

I take it lmao

vale root
#

just put the link no words

slate swan
#

wdym?

valid niche
#

A few messages down should explain enough

valid niche
#

Just like this

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
valid niche
#

Oh what do I see. In the constructor you can do activity= to safely set an activity upon logging in?

#

That seems rather convenient

vale root
#

When i did

embed = discord.Embed(title = f"[testing pizza](pizza.com)")

it did
[testing pizza]
(pizza.com)

valid niche
#

Make it a full valid URL

vale root
#

it was

valid niche
vale root
#

this is what i really printed

valid niche
vale root
#

Server Start Up Vote
Vote With the ✅ mark if you plan on attending.

Vote with a ❌ if you can not join.

If you vote with the check you must join when ssu opens if not you will be warned!

If you get warned and join the Sesh then you can dm a admin to get it taken away!

valid niche
#

See how it turns blue?

vale root
#

damn link

#

I want the words to be the hyper link so when i click the words Server Start Up that brings me to the link

#

Not the link

#

I dont want to see the link i want it to be so when i click those words it takes me to the link

valid niche
#

Whatever I don’t judge (unless you watch Lucas, use replit or any combination of the both)

vale root
#

I dont

#

this is for friends and somthing to do

#

So is there a way to hyper link the words Server Start Up so when i click them i get the link?

valid niche
#

I assume the field you used doesn’t support hyperlinks then

vale root
#

What feild

valid niche
#

In an embed only certain parts accept hyperlinks and I forgot which ones

#

I do believe title and footer didn’t allow hyperlinks

vale root
#

So dose description?

#

Ill test it in descrp

#

It worked in description

valid niche
maiden bronze
#

hey there, im coding a discord bot. I want to make it be able to have a different theme like red and blue ect could someone help me with that?

valid niche
maiden bronze
#

i could have 1 theme and design and stuff

valid niche
#

Theme where what when?

maiden bronze
#

and i can put the prefix then theme and make it a different theme

valid niche
#

Theme what?

maiden bronze
#

does that make sense?

valid niche
#

No

#

Because discord has no such thing as theme

maiden bronze
#

okay so like a different look

valid niche
#

Different look as in?

maiden bronze
#

different embed colour different gif ect

valid niche
#

You need to be more precise, exact and detailed with your question

valid niche
#

For a gif well if you send a gif you pick what gif to send

maiden bronze
#

yes but i want to be able to change it without editing the code itself and just typing lets say the prefix is .

#

i would type .theme 2 and it could change to a different embed colour

final iron
#

Can somebody link me the page for BucketType in the documentation I can't seem to find it

valid niche
#

Have you heard of: variables?

slate swan
maiden bronze
#

i know a tiny bit about variables

valid niche
unkempt canyonBOT
valid niche
slate swan
valid niche
#

Which I find a valid thing because I don’t see a reason to have message duplicated

valid niche
#

There is only message in that error

vague grove
#

hi, how can I detect when an image is sent & then do things with it (like post it in another channel or download it)

slate swan
#
    messages = await ctx.channel.history(limit=20).flatten()
    for msg in messages:
        print(msg.message)```
#

i'm trying to get the author of the message

#

msg.message gives me that error

vague grove
#

message.author
ctx.author?

slate swan
#

sure

vague grove
#

for the id

slate swan
#

that won't work here

vague grove
#

ah

slate swan
#

object has no attribute 'message'

vague grove
#

ih

#

oh

#

well what does this code do in the first place ;what are you trying to acheive

slate swan
#

got it

#

uprint(msg.author.id)

vague grove
#

ah

slate swan
#

hah my bad

#

doh

#
@client.command()
async def select(ctx):
    await ctx.send("This is a new feature!",
      components=[
        Select(placeholder='Select Something!', options=[SelectOption(label='A', value='a'), SelectOption(label='B', value='b')])
      ]
    )
    while True:
      interaction = await client.wait_for("select_option") 
      if interaction.values[0] == "a":
          await interaction.respond(content=f"You Clicked the `A` value!")  
      elif interaction.values[0] == "b":
          await interaction.respond(content=f"You Clicked the `B` value!")

why do i get interaction failed

vale root
#

Or from what im reading it has to be outside of the embed

slate swan
#

you cant mention in an embed

#

well you can but it wont ping

vale root
#

ok so after the embed How would i ping a role?

#

This is my embed code

slate swan
#

await ctx.send("code for role mention")

vale root
#
@commands.command(name="ssuvote")
    async def ssuvote(self,ctx):
        embed = discord.Embed(title = f"ServerStart Up Vote", description =f"Vote With the :white_check_mark: mark if you plan on attending." "\n" "\n" " Vote with a :x: if you can not join." "\n" "\n" f"[```Click here to get a link to ERLC```](url)" "\n""\n" "If you vote with the check you must join when ssu opens if not you will be warned!" "\n" "\n" "** If you get warned and join the Sesh then you can dm a admin to get it taken away!**")
        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')
        msg = await ctx.send(embed=embed) 
        await msg.add_reaction(":white_check_mark:")
        await msg.add_reaction(":x:")
        await ctx.message.delete()
#

ok

flint cipher
#
@bot.command(aliases = ['ask8', 'magic8'])
async def 8ball(ctx, *, question=None):
    random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', 'Nah, I wouldn\'t keep my hopes high on that', 'Highly Doubtful', 'Hell No']
    if question == None:
        await ctx.reply('Ask a question so that i can reply to it smh')
        return
    embed=discord.Embed(description=random.choice(random_answers), colour = discord.Color.blurple())
    embed.set_author(name = question, icon_url = ctx.author.avatar_url)
    await ctx.send(embed=embed)

it says invalid syntax in line 2, can someone please help?

slate swan
#

i'm just trying to simply ban a member by their ID #. how can i do this

#

do i have to loop through the whole ctx.guild.members list to find the id

stark hearth
#
random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', "Nah, I wouldn't keep my hopes high on that", 'Highly Doubtful', 'Hell No']

@bot.command(aliases = ['ask8', 'magic8'])
async def _8ball(ctx, *, question=None):
    responses = random.choice(random_answers)
    
    if question == None:
        await ctx.reply('Ask a question so that i can reply to it smh')
        return
    
  embed=discord.Embed(description=responses, colour = discord.Color.blurple())
  embed.set_author(name = question, icon_url = ctx.author.avatar_url)
  await ctx.send(embed=embed)

try this

vale pendant
#

Then you would have to call it by putting a underscore.

vale pendant
#

You can do that, but, inside bot.command() put name="8ball"

#

So you don't have to call it by the underscore

vague grove
#

how can I detect when an image is sent & then do things with it (like post it in another channel or download it)

cursive barn
unkempt canyonBOT
valid niche
#

Either through role.mention, which produces the raw format <@&id> or you can fill in that format yourself with the ID

visual island
valid niche
vale root
#

How can i make a command ping the author of who wrote the command?

median isle
#

I think? or I know

vocal cargo
#

async def on_message(msg):
_list = ['cringe','bean']
if any([i in msg.content for i in _list]):
await msg.delete(msg)
await msg.reply("stop")

#

doesn't work

vale root
#

!dcc

vocal cargo
#

TypeError: delete() takes 1 positional argument but 2 were given

#

in on_message
await msg.delete(msg)

vocal cargo
#

kk

tame topaz
#

Hi

#

Is ctx.channel.purge working?

vague grove
vocal cargo
#

in on_message
await msg.delete
TypeError: object method can't be used in 'await' expression

vale root
visual island
median isle
#

what is this issu

vale root
#

That deletes the message

median isle
#

my bot doesnt run!

vale root
visual island
red canopy
#

So I have this code here:

interaction = await client.wait_for('button_click', timeout=timeout - time.time())
await interaction.respond(content = 'You Clicked A Button')

If I don't include the second line, a button click will result in saying interaction failed
Does anyone know how to make it so the button does not require a response? (this uses discord-components button btw)

vale root
#

wait i dont have one in this bot lmao

tame topaz
vocal cargo
tame topaz
#

It’s not returning any error

vocal cargo
#

@client.listen() async def on_message(msg): _list = ['cringe','bean'] if any([i in msg.content for i in _list]): await msg.message.delete() await msg.reply("stop")

median isle
#

what the issue

vocal cargo
#

this doesn't work

stark hearth
stark hearth
#

usually you put it though

flint cipher
#
@bot.command(aliases = ['ask8', 'magic8'])
async def 8ball(ctx, *, question=None):
    random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', 'Nah, I wouldn\'t keep my hopes high on that', 'Highly Doubtful', 'Hell No']
    if question == None:
        await ctx.reply('Ask a question so that i can reply to it smh')
        return
    embed=discord.Embed(description=random.choice(random_answers), colour = discord.Color.blurple())
    embed.set_author(name = question, icon_url = ctx.author.avatar_url)
    await ctx.send(embed=embed)

it says invalid syntax in line 2, can someone please help?

visual island
flint cipher
#

oh ok
didnt see lel

stark hearth
#

its because of the async def 8ball

vocal cargo
stark hearth
#

you can't have a number starting @flint cipher

visual island
stark hearth
vocal cargo
#

i would think the message

#

im a little new

visual island
#

the message itself is msg

vocal cargo
#

so how 2 fix

visual island
#

remove the .message

vague grove
red canopy
#

@median isle i think you need an on_ready

@bot.event
async def on_ready():
  print('Bot Ready. Logged in as ' + bot.user.name)
vocal cargo
#

so just msg.delete

visual island
vocal cargo
#

@visual island

#

do i put ()?

visual island
#

sure

tame topaz
#

why isn't this working?

await ctx.channel.purge(limit=int(arg1) + 1)
visual island
#

any errors?

tame topaz
#

Nope

#

It was working fine yesterday...

vague grove
# visual island link?

when I post an image, then the bot catches it as a message.attachment, it says filename=filename and gives a link which gives an error

red canopy
vague grove
#

oh, it adds a series of %56%3% after the link.. is there any way to remove them?

visual island
#

what are you trying to do exactly?

tame topaz
vague grove
visual island
vague grove
visual island
vague grove
#

ah

#

its just the end, after the png or the jpg

#

hm..

sweet pilot
#
  File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/app/moddy/cogs/quiz.py", line 59, in on_raw_reaction_add
    msg = await channel.fetch_message(payload.message_id)
  File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/abc.py", line 1132, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

what missing perm can cause this?

slate swan
#

how can i get the bot to pick a random text channel then get the id from it

#

always getting termed for no reason smh @pure reef

sweet pilot
#

thx

visual island
tame topaz
# red canopy there are no issues with that statement, it is probably other parts of your code
@bot.command()
@has_permissions(administrator=True)
async def clear(ctx, arg1=None):
    global prefixs
    embed20 = discord.Embed(title=f"You have deleted {arg1} messages!",
                            color=0x1597BB)
    embed20.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
    embed21 = discord.Embed(title=f"Usage: {prefixs}clear `integer`",
                            color=0x1597BB)
    embed21.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
    embed21.add_field(name="An error occured",
                      value="The process has been `terminated`.",
                      inline=True)
    try:
        if arg1 == None or int(arg1) == 0:
            await ctx.channel.send(embed=embed21)
            return
        await ctx.channel.purge(limit=int(arg1) + 1)
        message = await ctx.channel.send(embed=embed20)
        time.sleep(3)
        await message.delete()
    except:
        await ctx.channel.send(embed=embed21)


@clear.error
async def clearerror(ctx, error):
    if isinstance(error, CheckFailure):
        embed21 = discord.Embed(
            title=f"You must be an admin to use this command!", color=0x1597BB)
        embed21.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
        embed21.add_field(name="An error occured",
                          value="The process has been `terminated`.",
                          inline=True)
        await ctx.channel.send(embed=embed21)
    else:
        return

still no error i can find

tame topaz
vague grove
ivory dome
#

hey

#

how do i make my bot delete spam?

#

can someone help me?

tame topaz
ivory dome
#

prevent spamming

#

@tame topaz

tame topaz
#

Oh

ivory dome
#

hello

#

?

slate swan
#

how can i make it so i have an argument but its not required

#
@bot.command()
async def welcfooter(ctx, message):
 try:
   if message is None:
    await ctx.send("Cleared welcome footer")
    db[f"{ctx.guild.id} footer"] = ""
   else:
    pass
  
   del db[f"{ctx.guild.id} footer"]
   db[f"{ctx.guild.id} footer"] = message
   await ctx.send(f"Set **{message}** as welcome footer")
 except:
   pass
  
``` isnt working
#

i thing the is None: is wrong tho

tame topaz
# ivory dome hello

You could try saving a list of past messages and compare them. Make sure it's from the same author

vale pendant
ivory dome
#

oh well

#

not much info but i'll take it

slate swan
tame topaz
vale pendant
slate swan
#

thx bro

vale pendant
#

wait

#

get rid of the *

ivory dome
slate swan
#

my problem is its putting None into the db

vale pendant
#

because you didn't return it

slate swan
#

explain plz if you dont mind

vale pendant
#

if you don't return it, it's going to continue

slate swan
#

so just put

#

return

vale pendant
#

so after you set the welcome footer to " " return

#

yes

slate swan
#

learned sum new thx

vale pendant
#

ofc

vast spindle
#

How do I make the bot check what kind of message it is for example pinging people/sending images

tame nymph
#

message.mentions length and message.attachments length

slate swan
#

How can I make a bot that send messages to a specific channel?
Example: ,up #test Note
And it send to #test channel

vast spindle
#

alright how can I check if a message is a link if possible

wicked atlas
#

Just a hunch

slate swan
#

Ye tysm I will figure it out, somehow haha

stark hearth
#

then await channel.send('')

slate swan
#

So I put (id= channel id?)

stark hearth
lyric moat
#

how can i make my bot leave a server? i do not owned

vale pendant
vast spindle
#

how can I check if a discord message contains a link

maiden fable
vast spindle
#

yeah idk what that is mate

lyric moat
#

when ever i try this i got an error


  @commands.command(hidden=True)
  @commands.is_owner()
  async def leave(self, ctx, guild: discord.Guild):
    await self.bot.leave_guild(guild)
    await ctx.send(f"I Had Left guild: {guild.name} ({guild.id})")```
stark hearth
vale pendant
#
  @commands.command(hidden=True)
  @commands.is_owner()
  async def leave(self, ctx, guildID: int):
    guild = await self.bot.get_guild(guildID)
    await guild.leave()
    await ctx.send(f"I Had Left guild: {guild.name} ({guild.id})")```
#

this should work

stark hearth
stark hearth
maiden fable
stark hearth
stark hearth
vale pendant
#

my bad

#

typo error

maiden fable
#

Only fetch methods need to be awaited

stark hearth
lyric moat
#

how i stop it from doing this?

#
@client.command()
@commands.has_permissions(manage_messages=True)
async def poll(ctx, user: discord.Member = None):
      if user is None:
          await ctx.send(f"{ctx.author} you must mention a user to do that!")
      else:
 
       icon_url = ctx.author.avatar_url 
 
      pollEmbed = discord.Embed(title = "New knowed poll", description = f"**Is Knowed/UnKnowed**\n\n![zzhoodvoteyes](https://cdn.discordapp.com/emojis/887160017973813258.webp?size=128 "zzhoodvoteyes") - **Knowed**\n![heartbroke_no](https://cdn.discordapp.com/emojis/887160052698447912.webp?size=128 "heartbroke_no") - **Unknowed**",colour=0x2f3136)
      pollEmbed.set_thumbnail(url=f"")
    
      pollEmbed.set_footer(text = f"Poll requested by{ctx.author}")
  
      await ctx.message.delete()
 
      poll_msg = await ctx.send(embed = pollEmbed)
 
      await poll_msg.add_reaction("![zzhoodvoteyes](https://cdn.discordapp.com/emojis/887160017973813258.webp?size=128 "zzhoodvoteyes")")
      await poll_msg.add_reaction("![heartbroke_no](https://cdn.discordapp.com/emojis/887160052698447912.webp?size=128 "heartbroke_no")")```
twilit tusk
#

One question... How can I add roles using the role ID?

vast spindle
#

how can I check if a discord message contains a link

slate swan
#

Stop sending the embed when no user is mentioned?

slate swan
ocean leaf
#

how do i send message in a channel by knowing the channel id only?

winter jetty
#

Hey guys, i'm trying to turn the binary from gateway.discord.gg to human readable format

I've tried a bunch of stuff, but have no idea how to do this

b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'

An example of binary received

ocean leaf
#

discord devs and discord api. thay have bot for discord server too

slate swan
unkempt canyonBOT
wispy spade
slate swan
#

Use this and .send

ocean leaf
paper bane
ocean leaf
#

and i have to pass the id in the foem of string?

#

i can give u link

ocean leaf
#

ok

ocean leaf
slate swan
#
@bot.command(name='play', aliases=['p'])
async def play(ctx,url):
    voice_client = ctx.message.guild.voice_client

    if voice_client.is_connected():

    else:
        server = ctx.message.guild
        voice_channel = server.voice_client```

i want it to ignore the next part if the first part is true, how would i do that?

(sorry idk how to format it to python i'm slow)
#

i'm still kinda bad at python lmfao

#

use return in the if

ocean leaf
slate swan
#
if <something>:
   return```
ocean leaf
#

i can't create invite for bots for dscord

slate swan
#

They might have a link in their info channel :3

ocean leaf
#

this may help too :)

#

np

#

get_channel is not defined

slate swan
#

Channel = client.get_channel(id)

ocean leaf
#

ok

night onyx
#

can i use the sqlite and aiosqlite both at the same time
im making per server prefixes i know it only with sqlite
but if there any solution regarding per server custom prefix with aiosqlite then pleasse tell me that also

ocean leaf
#

is it possible to tag a channel by it's id in dpy? for ex i have the id of python-general and i want to tag the channel like this #python-discussion is it possible to do this by my dpy bot?

#

if there is a docs page for that?

night onyx
#

yes its possible

ocean leaf
#

pls tell me

night onyx
#

if you want mention channel by context then ctx.channel.mention

#

check your indentaion @slate swan

winter jetty
#
import asyncio
import base64
import secrets
from json import load

import aiohttp


ws_key = base64.b64encode(secrets.token_bytes(16)).decode('utf-8')
headers = {
    'Pragma': 'no-cache',
    'Origin': 'https://discord.com',
    'Accept-Language': 'en-US,en;q=0.9,es;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Sec-WebSocket-Key': ws_key,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/93.0.4577.63 Safari/537.36',
    'Upgrade': 'websocket',
    'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
    'Cache-Control': 'no-cache',
    'Connection': 'Upgrade',
    'Sec-WebSocket-Version': '13',
}


async def go():
    from main import buffer, inflator
    session, ws = None, None
    try:
        with open('first_message.json') as file:
            to = load(file)
        session = aiohttp.ClientSession()
        ws = await session.ws_connect(url='wss://gateway.discord.gg/'
                                          '?encoding=json&v=9&compress=zlib-stream',
                                      headers=headers)
        msg = await ws.receive()
        print(msg.data)
        await ws.send_json(to)
        async for msg in ws:
            print(msg)
            buffer.extend(msg.data)
            print(inflator.decompress(buffer))

    finally:
        if ws:
            await ws.close()
        if session:
            await session.close()


if __name__ == "__main__":
    asyncio.run(go())
#
import zlib


ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
#

The error:

Traceback (most recent call last):
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
    asyncio.run(go())
  File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
    print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
#

I tried this earlier, @paper bane @wispy spade

wispy spade
winter jetty
wispy spade
winter jetty
#

Also, I've taken just the bytes, tried to decompress that, and got the same error message

wispy spade
#

hmm, maybe in the for loop, try resetting the buffer back to a bytearray() after you're done with that msg.

slate swan
#

is it on_guild_remove or on_guild_leave

spring flax
#

what do you want it for?

slate swan
#

when it leaves a server it sends a embed to a specified channel

#

im guessing its leave but i could be incorrect

stuck flare
#

!ctx

slate swan
#

something like that

stuck flare
#

!discord.Context

#

nvm

slate swan
#

What did you need though.

winter jetty
slate swan
#

how do i get an error of a cm like this

@bot.event
async def on_member_join(member):
  try:
    a = db[f"{member.guild.id} welc"]
    t = db[f"{member.guild.id} footer"]
    h = bot.get_channel(a)
    l = db[f"{member.guild.id} msg"]
    embed = discord.Embed(description=l,color=discord.Color.blurple)
    embed.set_footer(text=t)
    await h.send(embed=embed)
  except:
    await h.send(f"**ERROR, this error is being reported to the developers, it will be fixed in a range from** `1.5 - 6 days`")
wispy spade
winter jetty
# wispy spade Weird, any errors with that?

The same one, this:

Traceback (most recent call last):
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
    asyncio.run(go())
  File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
    print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
wispy spade
#

hmm

slate swan
#

Anyone know how can I let the bot send messages to a specific channel on channel mention?

spring flax
#

yes as the command arguments type hint one to arg : discord.TextChannel and then do arg.send()

slate swan
#

Wait I'll try

slate swan
spring flax
#

you won't be able to do it for events

#

but which error do you want to handle

frosty prairie
#

Ofc /:

#

I did

slate swan
boreal ravine
#

@frosty prairie code?

slate swan
#
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.CommandInvokeError):
    log = bot.get_channel(887187090037702656)
    await ctx.send(f"```py\n{error}```")
    await log.send(f"**GUILD ID; {ctx.guild.id}**\n ```py \n{error}```")
``` nothing would send
spring flax
slate swan
#

i got it

#

for one cmd at least

#
embed = discord.Embed(description=l,color=discord.Color.blurple)
``` whats wrong abt this
#

Why blurple

#

like the color

#

Ohh

frosty prairie
# boreal ravine <@813420921980715028> code?
    file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png')
    embed = discord.Embed(title='..')
    embed.set_image(url="attachment://king_of_diamonds.png")
    message = await ctx.send(embed=embed, file=file)
    await message.add_reaction('🤙')
    fetch = await message.channel.fetch_message(message.id)
    print(fetch.reactions)
    def check(reaction, user):
        return reaction.emoji == "🤙", user == ctx.author


    msg = await bot.wait_for('reaction_add', check=check)
   
    embed2= discord.Embed(title='..')
    embed2.set_image(url="attachment://king_of_diamonds.png")
    file2 = discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png')
    await message.edit(embed=embed2, file=file2)
#

it sends file but while editing, it gives error tho same file

vagrant brook
#

what error

frosty prairie
slate swan
#

should i embed all that stuff then it sends ?

spring flax
slate swan
vast spindle
#

how can I check if a discord message contains a link or emoji

slate swan
#

how do i get the role spot of the bots top role vs a role

#

like if the bots role isnt over another role

#

nvm

gloomy quest
#

hi

#

Does anyone know how to use subreddits

spring flax
tight patrol
#

just made my bot run forever, feeling good

slate swan
#

how can i add guild icon in embed?

sick talon
slate swan
#

at the top of embed

sick talon
#

ohh ok
you can get the link of the guild's icon by ctx.guild.icon_url

slate swan
#

oh ok lemme try

slate swan
sick talon
slate swan
sick talon
slate swan
#

Here like this

sick talon
slate swan
#

i was about to ask can i use set_author
But lemm try

slate swan
#

Nope it doesn't show the guild icon

#

Here is the results

#

Here is the code

Ignore the red underline it's a bug

#

Does the guild have an icon

#

Not the default one

#

If it doesn't have one then it will return None

#

Try adding some random pic to your guild's icon

#

oh shoot my bad, the server doesnt have an icon

#

That's why

#

tysm for telling

#

Yw

#

thanks @NotMrBugcat#3246, @Kraots#3999

sick talon
sick talon
lone aurora
#

in embeds, i want to use the color #090303 do i just do |
color = "#090303"?

slate swan
#

is it add_role or add_roles

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

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

ic ok

#

thanks mate

slate swan
#

Yw

#

thoughts ?

spark harbor
#

Hi guys, who can help me to build opensea discord bot?

slate swan
#

?

#

!rule 5

unkempt canyonBOT
#

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

elder python
#

while using mongo motor with discord.py is this required

import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())
result ObjectId('...')
boreal ravine
stark hearth
slate swan
stark hearth
slate swan
#

mhm

#

test to make sure the on_member_join event is working

stark hearth
#

i usually test my bot with a ping command

#

it looks like this

boreal ravine
#

@slate swan who's alt are you?

slate swan
#

@pure reef termed or sum idk i got phone locked

boreal ravine
#

o

slate swan
#

good setup?

stark hearth
#

mine looks similar to this

lyric moat
#

why does here gives and error?

slate swan
#

your indentation

stark hearth
lyric moat
#

i did every time i did it it does this

stark hearth
#

lets see the code

slate swan
#

yep

stark hearth
#

we'll try to help

lyric moat
slate swan
#

i suggest you use

lyric moat
#

alright

slate swan
#

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

stark hearth
#

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

slate swan
lyric moat
stark hearth
exotic patrol
stark hearth
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.
lone gulch
#

HEy

#

Hey i need help

lyric moat
stark hearth
exotic patrol
lone gulch
#

How to fix this

lyric moat
#

Got This

stark hearth
stark hearth
lone gulch
#

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

stark hearth
stark hearth
lone gulch
#

yu

#

yup

stark hearth
lyric moat
stark hearth
# lyric moat Same Line As?

move ChannelMessageWithSource up with the InteractionType. so it would make InteractionType.ChannelMessageWithSource

lone gulch
#

there was saying to install so i dowloaded from phython.org

boreal ravine
#
@client.command()
async def ban(ctx, member: commands.MemberConverter, reason=None):
  try:
    if not reason:
      embed=discord.Embed(description=f'You have been banned in **{ctx.guild.name}**.')
      await member.send(embed=embed)
      await ctx.guild.ban(member)
      embeder=discord.Embed(description=f'{member} was banned.')
      await ctx.send(embed=embeder)
    else:      
      embed=discord.Embed(description=f'You have been banned in **{ctx.guild.name}** for {reason}.')
      await member.send(embed=embed)
      await ctx.guild.ban(member)
      embeder=discord.Embed(description=f'{member} was banned.')
      await ctx.send(embed=embeder)
  except:
    embed=discord.Embed(description='Member can\'t be banned.')
    await ctx.send(embed=embed)
``` This is my ban command as of now and it works but if your the server owner like me it still DMs you even if you didn't get banned. How do I fix this?
stark hearth
#

or was it a typo

stark hearth
lyric moat
#

But Every Time I tried it gives this

lone gulch
boreal ravine
lyric moat
#

its there

boreal ravine
#

No thats a dot

lone gulch
#

how to import discord

lyric moat
#

at Type Channel?

#

Or At The End?

stark hearth
boreal ravine
stark hearth
#

then in code type import discord

boreal ravine
lyric moat
lone gulch
#

pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • pip install discord.py
  •   + CategoryInfo          : ObjectNotFound: (pip:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
lyric moat
#

but ended up with this

boreal ravine
stark hearth
#

if that does not work you do not have pip installed or python installed

lone gulch
#

how to go to command prompt

lyric moat
#

Why When I put a . at

type=InteractionType.ChannelMessageWithSource,```
it gives red line to the code but when i try
```py
type=InteractionType,ChannelMessageWithSource,```
it takes off error
boreal ravine
slate swan
#

how to get a users about me or banner thing

boreal ravine
slate swan
#

don't know how

boreal ravine
#

await bot.fetch_banner(id) ig

stark hearth
lyric moat
#

So how i fix this now?

slate swan
boreal ravine
boreal ravine
slate swan
#

ohh

#

what to do with that

stark hearth
lone gulch
#

pip' is not recognized as an internal or external command,
operable program or batch file.

stark hearth
#

did you do this from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType

#

@lyric moat

lyric moat
#

no

stark hearth
#

put that in the beginning of the code

slate swan
lyric moat
boreal ravine
lone gulch
# boreal ravine did u try what I said?

yup Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

lyric moat
boreal ravine
slate swan
#

scratch that how do i see how many people are offline, online, and how many bots

lyric moat
#

i tried put that but it would not work should i put it in the cog too?

slate swan
#

!d discord.Member.status

unkempt canyonBOT
#

status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
stark hearth
boreal ravine
stark hearth
slate swan
stark hearth
slate swan
#

nor who's online

lyric moat
#

i keep getting this..

lone gulch
# stark hearth put that in terminal

it is saying Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

slate swan
#

how do i get the offline members and online members that's all i need to know.

slate swan
#

for one guild

ocean leaf
#

how do i get the date when my server was created? guild.created_at?

stark hearth
slate swan
#

okay enabled them

lyric moat
slate swan
#

ctx.guild.created_at

boreal ravine
unkempt canyonBOT
stark hearth
ocean leaf
slate swan
#

it's repl idk if they work in repl

boreal ravine
#

wdym?

#

Just use the shell in replit?

slate swan
#

idk if discord components work in repl

slate swan
boreal ravine
#

they do lmfao

boreal ravine
stark hearth
#

my head is in many directions

slate swan
#

click space once or twice

stark hearth
#

indentation

ocean leaf
boreal ravine
#

!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

slate swan
#

the if message.content isn't in the function

boreal ravine
#

Indents are 4 spaces

boreal ravine
ocean leaf
#

idk if i am dumb or not

stark bobcat
#
@bot.event
async def on_message(message: discord.Message):
  if message.guild is None and not message.author.bot:
    print(message.content)  
    print(message.author)

    embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
  
    a=await message.author.send(embed=embed)
    await a.add_reaction('\u2705')
    await a.add_reaction('\U0001f6ab')

    def check(reaction, user):
      return user == message.author and str(reaction.emoji) in ['\u2705','\U0001f6ab']

    reaction, user = await bot.wait_for('reaction_add',check=check)

    print(reaction.emoji)

why does't it print the reaction the user reacted on?

ocean leaf
boreal ravine
slate swan
#

Please reset your token you just showed it to everyone

#

guild = ctx.guild
await ctx.send(guild.created_at)

boreal ravine
#

Use the shell @lyric moat

#

Do you know what the shell is?

lyric moat
#

where?? thats on repl?

boreal ravine
#

you should see it

slate swan
#

can't u just do os.system("pip install (whatever)")

lyric moat
#

nope i do not see it

boreal ravine
stark bobcat
boreal ravine
ocean leaf
#

why is it arranged in this shitty way?

stark hearth
lone gulch
# stark hearth ^^^

help me File "c:\Users\prani\Desktop\Nova Client\Nova Client.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
PS C:\Users\prani\Desktop\Nova Client>

lyric moat
#

alr i see it

boreal ravine
ocean leaf
stark hearth
lyric moat
#

so i put pip install discord-buttons
in the shell?

ocean leaf
#

in ur terminal

lone gulch
#

in terminall ?

ocean leaf
boreal ravine
ocean leaf
#

like cmd

boreal ravine
ocean leaf
boreal ravine
slate swan
#

use description

lyric moat
#

this what i got

slate swan
#

that's what i do most of the time

lyric moat
slate swan
#

bro...

boreal ravine
ocean leaf
boreal ravine
#

indents

slate swan
#

u have all the wrong shit outa place

boreal ravine
#

y .format use f strings my eyes bleed

#

no. spoon. feeding.

ocean leaf
#

u wrote the last part outside the on_message function

slate swan
#

bro... it's a simple ident error

#

click space until the error is fixed

stark bobcat
#

just tab

stark hearth
ocean leaf
slate swan
#

It's a simple indent error you should be able to fix that yourself pretty easily

ocean leaf
#

it is extremely to fix

lyric moat
#

the whole thing does not even respond

boreal ravine
#

by how

lyric moat
#

It said not command found test

slate swan
#

Have you tried installing discord-components from the package manager?

boreal ravine
lyric moat
#

and the name is test

stark hearth
#
if message.content.startswith('Good afternoon'):
   await message.channel.send('Good afternoon! I am Newton’s Bot and nice to meet you!')
   await message.channel.send(random.choice(note))```
highlight that and press tab
slate swan
stark bobcat
lyric moat
#

it keeps showing red line and it does not show error but just not answer the command

slate swan
#

BRUHHH I JUST FINISHED MONEY HEIST NOW I GOTTA WAIT TILL DECEMBER THIRD

lyric moat
stark bobcat
slate swan
stark bobcat
#

and just forgot about it

slate swan
#

huh

ocean leaf
slate swan
#

You need to import them from discord-components

slate swan
ocean leaf
boreal ravine
#

I thought he meant the date 💀

slate swan
#

But why use a 3rd party lib that's breaking iirc instead of just using the master version which also had selects 😟

#

a kwarg for add field

boreal ravine
slate swan
#

yeah

slate swan
stark hearth
#

my indents are suffed ik

stark bobcat
#

ok thanks

ocean leaf
slate swan
#

!d

unkempt canyonBOT
slate swan
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

slate swan
#

^

#

Or in your case for the embed

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

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

i was looking at my bot

stark hearth
#

just do except

#

code?

stark bobcat
unkempt canyonBOT
#

Hey @slate swan!

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

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

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

https://paste.pythondiscord.com

stark hearth
#

yeah

#

do

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

  if message.content.startswith('Good afternoon'):
    await message.channel.send('Good afternoon! I am Newton’s Bot and nice to meet you!')
    await message.channel.send(random.choice(note))
#

add @client.event to your on_ready

#

also for the last line it needs to be client.run(os.environ['DISCORD_TOKEN'])

#

not client.run(os.getenv('DISCORD_TOKEN'))

slate swan
stark hearth
#

but just for organization, you can do that

#

does it work @slate swan

#

take your time

#

im asking after this i need to sleep for an exam

#

error?

#

like this ^^^

#

send that part after running the script

#

like it is running but the bot is not responding?

maiden fable
unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3.10/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3.10/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3.10/library/intro.html#availability): most flavors of Unix, Windows.
maiden fable
#

Not saying anything to u dw

supple thorn
#

You dont have @client.event

stark hearth
supple thorn
#

Also thats the wrong event

maiden fable
stark hearth
maiden fable
stark hearth
maiden fable
#

!d os.environ

unkempt canyonBOT
#

os.environ```
A [mapping](https://docs.python.org/3.10/glossary.html#term-mapping) object representing the string environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.

This mapping is captured the first time the [`os`](https://docs.python.org/3.10/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in `os.environ`, except for changes made by modifying `os.environ` directly.

This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3.10/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
stark hearth
#

im dosing off rn my bad

spring flax
supple thorn
#

Yeah

maiden fable
#

😂

stark hearth
supple thorn
#

on_message

stark hearth
hasty loom
#

oh nevermind im so stupid

maiden fable
#

Show yr load function

supple thorn
#

You loaded it right?

maiden fable
#

Uhhh?

hasty loom
supple thorn
hasty loom
#

im stupid lol

maiden fable
#

Haha

stark hearth
#

use bot.run(os.getenv('DISCORD_TOKEN'))

waxen granite
#

how do avoid microseconds in timedelta?

stark hearth
#

you are using an .env file to cover your token

#

reload

stark bobcat
#
@bot.event
async def on_message(message: discord.Message):
  if message.guild is None and not message.author.bot:
    print(message.content)  
    print(message.author)

    embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
  
    a=await message.author.send(embed=embed)
    await a.add_reaction('\u2705')
    await a.add_reaction('\U0001f6ab')

    def check(reaction, user):
      return user == message.author and str(reaction.emoji) in ['\u2705','\U0001f6ab']

    try:
      reaction, user = await bot.wait_for('reaction_add',check=check)
      print(reaction.emoji)
    except:
        pass```
wispy sequoia
#
@client.command()
async def coinflip(ctx):
    faces = ["heads", "tails"]
    choice = random.choice(faces)

    embed = discord.Embed(color=0x000000)
    embed.add_field(name="\U0001fa99 Spinning...",
                    value="`Please wait`", inline=False)

    new_embed = discord.Embed(color=0x000000)
    new_embed.add_field(name="\U0001fa99 Coinflip",
                        value=f"<@!{ctx.author.id}>, you got **{choice}**", inline=False)

    wait = await ctx.reply(embed=embed, mention_author=False)
    await asyncio.sleep(2)
    await wait.edit(embed=new_embed)```
did I make anything wrong? bc it's choosing tails everytime .-.
stark hearth
#

im sorry @stark bobcat @slate swan but i need to sleep

wispy sequoia
maiden fable
#

It's choosing tails cz random module likes tails 😂

wispy sequoia
#

lmfao

stark hearth
#

im sorry

slate swan
#
    @flags.add_flag('-n','--number')
    @orbs.command()
    async def use(self,ctx,message,**flags):
       orbs=flags['number']```

why i m getting key error number in this
stark hearth
#

bye bye

stark bobcat
#

bye

maiden fable
waxen granite
#

how do i avoid printing microseconds in time delta?

stark bobcat
maiden fable
#

Ah ok thanks

wispy sequoia
# stark bobcat ye
@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        await message.channel.send("Leave. Me. Alone. Dumbass.")
        await message.add_reaction(emoji="\U0001f1e9")
        await message.add_reaction(emoji="\U0001f1ee")
        await message.add_reaction(emoji="\U0001f1ea")
        return

    if message.author == client.user:
        return await client.process_commands(message)

    if message.author.bot:
        return await client.process_commands(message)

    ctx = message.channel
    await client.process_commands(message)```
this is on bot mention
#

from my bot

stark bobcat
#

oh

stark bobcat
wispy sequoia
#

hm

#

is there a way to make discord say "bot is thinking"

#

like with slash commands

maiden fable
tame topaz
stark bobcat
maiden fable
#

Lemme see

wispy sequoia
maiden fable
lone aurora
stark bobcat
#

should i do like

wispy sequoia
stark bobcat
#

except Exception as e:
print(e)?

lone aurora
#

thats on u lmamo

maiden fable
stark bobcat
wispy sequoia
#
    wait = await ctx.reply(embed=embed, mention_author=False)
    async with ctx.typing():
        await asyncio.sleep(2)
    await wait.edit(embed=new_embed)```
this triggers typing but doesn't stop after the sleep @maiden fable
stark bobcat
maiden fable
wispy sequoia
maiden fable
stark bobcat
#

hm

#

only this

keen talon
#

\😬

keen talon
maiden fable
#

Yea

keen talon
#
str(emoji)=="😬"
maiden fable
#

Yea

valid galleon
#

so im thinking of making a whois/ui command for my bot, and i was wondering if theres a way to see how many messages theyve sent in a server without a db?

silver wolf
#

no there isnt a way to do that with d.py

lament mesa
silver wolf
#

if its for a personal server depending how old it is. i suppose. if its for a public bot, not possible. or i guess...it technically is, but that'll take weeks

summer jungle
#

Ayo how do you make a command Case Insensitive?

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
summer jungle
#

Okay

dense swallow
#

so im trying to make something which Dyno bot has in the whois command... how can i get a user's permissions (if they have it) ?

#
perms = []
        key_perms = {
            'administrator': 'Adminstrator',
            'ban_members': 'Ban Members',
            'kick_members': 'Kick Members',
            'manage_guild': 'Manage Server',
            'manage_channels': 'Manage Channels',
            'view_audit_log': 'View Audits',
            'manage_messages': 'Manage Messages',
            'manage_nicknames': 'Manage Nicknames',
            'manage_roles': 'Manage Roles',
            'manage_permissions': 'Manage Permissions',
            'manage_webhooks': 'Manage Webhooks',
            'manage_emojis': 'Manage Emojis',
            'mention_everyone': 'Mention Everyone',
            'deafen_members': 'Deafen Members',
            'mute_members': 'Mute Members',
            'move_members': 'Move Members',
        }
``` i have this much rn... now what??
lament mesa
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

permissions_for(member)```
Handles permission resolution for the current [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member").

This function takes into consideration the following cases...
silver wolf
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.Permissions "discord.Permissions").

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

that will return the members permissions for the text channel

dense swallow
lament mesa
#

do you want guild wide?

dense swallow
#

yes

silver wolf
#

!d discord.ext.commands.has_guild_permissions

unkempt canyonBOT
#

discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").

New in version 1.3.
dense swallow
lament mesa
#

Check the permissions of the members top_role

silver wolf
dense swallow
#

yes

silver wolf
#

i think ur looking for

#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use either [`permissions_in()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.permissions_in "discord.Member.permissions_in") or [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
dense swallow
#

hmm

drifting arrow
#

Using a command, how would I cycle through a list 1 item at a time? I can't seem to get itertools cycle to work

#

maybe i'm doing something wrong ;-;

valid perch
#

You could just keep a pointer/index into the list and increment it each time ig

drifting arrow
#
@commands.command(help='[Starts a given task.]',aliases=['ff'])
    async def funfact(self,ctx):
        iteration = itertools.cycle(["A", "B", "C!"])
        await ctx.send(next(iteration))
hasty iron
#

a for loop?

drifting arrow
#

no i dont want to have the entire thing display at once..

hasty iron
#

use a for loop

drifting arrow
#

I want to be like $ff and it gives me "A" then $ff again and i get B

hasty iron
#

oh

drifting arrow
#

I dont want all 3 at once

valid perch
#

Well, you define the cycle within the command, so it'll point at the first item all the time

#

DDefine it out of it and should be fine

drifting arrow
#

I've never used itertools before.

valid perch
#

You already do.

#

Just don't do it in the command

drifting arrow
#

Alright

#

😮 you're right! @valid perch ty

silver wolf
#

put the iteration variable as an attribute of the class an re-use it

drifting arrow
#

Yep. ty ^_^ it was just in the wrong spot

near magnet
valid perch
drifting arrow
#

Oh boy my fun facts bot is gonna be lit yo

#

Friends gonne love me this weekend 😉

heavy radish
#

How do I get my embed to go on the next line

#

Like currently its like
Current Ping
??Ping Aliases: ping or PING

I want
Current Ping
??Ping
Aliases: ping or PING

valid perch
#

\n (new line character)

heavy radish
#

So i just do that in my code?

valid perch
#

Correct

heavy radish
#

oki

drifting moss
#
            if len(message.mentions) > 5:
                #if message.author.guild_permissions.manage_messages:
                        #return
                await message.delete()
                role = discord.utils.get(message.guild.roles, name="Muted")
                await message.author.add_roles(role, reason="Automod muted for Mass Mention (5m)")
                embed = discord.Embed(title=f"AutoMod Muted {message.author.name}",
                                      description=f"reason : Spamming", colour=discord.Color.red())
                log_channel = self.bot.get_channel(863000643303374920)
                await log_channel.send(embed=embed)
                await asyncio.sleep(1)
                await message(
                    f"{message.author.mention} Don't Mass Mention! You Have Been Muted in Server for 5m")
                await asyncio.sleep(300)
                await message.author.remove_roles(role, reason="Automatic unmute for spam")

message.mentions is not working?? or not triggering?

valid perch
#

define 'not working'

drifting moss
#

no erros.

valid perch
#

Theres no reason that would error? hahahaha

#

Have you tried printing its length, or the list itself

drifting moss
valid perch
#

if statements don't throw errors if there false, but hey. Not my place
Have you tried printing its length, or the list itself

drifting arrow
#

so maybe it is triggering. try just having the bot in line 1 after the if, say "Triggered!"

dense swallow
# silver wolf !d discord.Member.guild_permissions

so like this?

        perms = []
        full_perms = member.guild_permissions
        key_perms = {
            'administrator': 'Adminstrator',
            'ban_members': 'Ban Members',
            'kick_members': 'Kick Members',
            'manage_guild': 'Manage Server',
            'manage_channels': 'Manage Channels',
            'view_audit_log': 'View Audits',
            'manage_messages': 'Manage Messages',
            'manage_nicknames': 'Manage Nicknames',
            'manage_roles': 'Manage Roles',
            'manage_permissions': 'Manage Permissions',
            'manage_webhooks': 'Manage Webhooks',
            'manage_emojis': 'Manage Emojis',
            'mention_everyone': 'Mention Everyone',
            'deafen_members': 'Deafen Members',
            'mute_members': 'Mute Members',
            'move_members': 'Move Members',
        }

        for permissions, user_perms in key_perms.items():
            if permissions in full_perms:
                perms.append(user_perms)

        if perms:
            em.add_field(name='Key Permissions', value=', '.join(perms), inline=False)
drifting arrow
#

Why wont this work? ```py
async def funfact_add(self,ctx, *, ff, type):

#

i try and run it and it says missing argument.

hasty iron
#

inside a command signature you cant have two keyword arguments

drifting arrow
#

I can.

#
async def funfacts_settings(self, ctx, setting = None, update = None):
```works.
hasty iron
#

there are no keyword arguments there

dry pelican
#

i'm getting the user id when i'm mentioning the bot through discord.py embed. Please help

drifting arrow
dry pelican
slate swan
#

it should

slate swan
hasty iron
dry pelican
#
embed.set_footer(text = f"Powered By {client.user.mention}")
#

like this

hasty iron
drifting moss
dry pelican
#

help :/

slate swan
drifting moss
#

btw bot can mute me

dry pelican
dry pelican
heavy radish
#

How do I use underlines on embeds??

slate swan
drifting moss
slate swan
#

__text__

dry pelican
#

so.... how do i do it?

heavy radish
#

__

#

Doesnt work..

thorny flint
#

So the thing is,
I'm trying to use a function outside the main function, inside a class.

functions.py
class functions(commands.Cog):
  def __init__(self, bot):
        self.bot = bot

  async def account_stats(self, access_token: str, accountId: str):
    gtResult = self.getPowerLevel(items)
    Level = gtResult[0]
    
    return Level
    ...
  

  def Power(self, items):
      ... 
    return Power

main file

from tests.functions import functions as fn
class stats(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def stats(self, message, userName=None,):
    ...
    stats = await fn.account_stats(access_token=access_token, accountId=account_id)
    ...

But that way, it would give me the error: ```TypeError: account_stats() missing 1 required positional argument: 'self'

but if I add `self`, like this
`stats = await fn.account_stats(self, access_token=access_token, accountId=account_id)`
I will instead get this error

AttributeError: 'stats' object has no attribute 'getPowerLevel'


Am I using the `self` wrong or?
Using cogs btw
drifting moss
#

umm in footers only text is there not mentions

silver wolf
heavy radish
#

Any other syntax

silver wolf
#

a little. close though

hoary fog
willow vine
#
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/message.py", line 1262, in remove_reaction
    await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

I'm trying to remove reaction from a message

spring flax
#

bot does not have the permissions (discord perms) to remove it

willow vine
#

how do i give the bot perms?

drifting arrow
#

Now to get some ~fun facts~

hoary fog
#

File "c:/Users/User/Downloads/discord bot/main.py", line 4, in <module> from music_bot import Player ImportError: cannot import name 'Player' from 'music_bot' (c:\Users\User\Downloads\discord bot\music_bot.py)

#

``
import discord
from discord import player
from discord.ext import commands
from music_bot import Player
intents=discord.Intents.default()
intents.members=True

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

@bot.event
async def on_ready():
print(f"{bot.user.name}is ready to use.")

async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))

bot.add_cog(Player(bot))
bot.run("")``

spring flax
willow vine
#

i gave the bot admin perms