#discord-bots

1 messages · Page 602 of 1

west shuttle
#

there is another way to upload cog with class?

slate swan
#

error -

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/My-First-Program/cogs/Fun.py", line 181, in write
    channelsend = discord.utils.get(channel_id)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/utils.py", line 291, in get
    for elem in iterable:
TypeError: 'int' object is not iterable

code -

channel_id = int(channel_id)
channelsend = discord.utils.get(channel_id)
await channelsend.send(f"{args}")
await ctx.message.delete()

do someone know why?

rustic temple
#

hey did they change they way you invite a bot to your server?

west shuttle
rustic temple
#

im on the oauth screen but i dont see an invite link

sullen shoal
rustic temple
#

nvm

slate swan
west shuttle
sullen shoal
west shuttle
#

thxx

slate swan
#

תודה אגב

west shuttle
sullen shoal
unkempt canyonBOT
#

bot.py lines 26 to 28

for cog in pkgutil.iter_modules(["cogs"]):
    bot.load_extension(f"cogs.{cog.name}")
    print("Loaded cog: {}".format(cog.name.title()))```
slate swan
west shuttle
sullen shoal
#

where are you doing it

west shuttle
sullen shoal
west shuttle
#

Okie

tawdry pilot
#

Hey so i have changed the profile picture of my bot on the developer portal but it hasnt changed on discord yet and that was like 3 hours ago

west shuttle
tawdry pilot
#

oh

#

damn i do not know stuff

#

thanks

west shuttle
#

lol

#

np

dusk dust
#

im making a bot command... ```py
nick = await ctx.author.send('type ur minecraft nick')
r_nick = await bot.wait_for("message", check=check)

if ' ' in r_nick:
    await ctx.author.send('**error** this minecraft ign is not found')
    nick = await ctx.author.send('type ur minecraft nick correctly')
    r_nick = await bot.wait_for("message", check=check)
else: pass
sullen shoal
#

cant help with that then

slate swan
#

can anyone just give the source code of a music bot? (as a cog)

#

No we don't give code

#

rip

#

Note that music bots are against YouTube's terms of service

#

And therefore breaks rule number 5

#

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

slate swan
#

ohh ok

rain jay
#

is there an event to detect whenever someone boost the server?

slate swan
#

I tried to run my code and an error popped up

#

so this was my code:

#

embedVar.add_field(name="Solve Puzzle", value='l!puzzle', color = 0xE95124)

hollow agate
#

Would this work: py if srmod or jr admin or admin in ctx.author.roles: work if the user has one of those in their roles?

#

(I'm defining the roles elsewhere)

slate swan
#

OH NVM I UNDERSTAND WHY

formal pollen
#

!e

print("HELLO ")
unkempt canyonBOT
#

@formal pollen :white_check_mark: Your eval job has completed with return code 0.

HELLO 
slate swan
#

I'm attempting to get the number of reactions on each of the past 200 messages but it's not rly working

#

What's a better way to resolve this issue?

boreal ravine
#

whats the issue

brittle ingot
#

do you need to fetch the message though?

slate swan
#

When I run the program, r Count isn't printing (print statement is inside an if statement btw)

slate swan
brittle ingot
#

you already have the message object though? from the for loop? or am i just being stupid.

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

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

Examples

Usage...
sage otter
#

Yeah I don’t know why you're fetching for

#

You get a sequence or something of message objects from that

slate swan
#

I tried it without fetch but that isn't working too

brittle ingot
#

did you import utils? is it supposed to be utils.get?

slate swan
#

I imported utils

brittle ingot
#

i guess you could do it the long way?

reactions = message.reactions
for reaction in reactions: 
    if str(reaction.emoji) == ":thumbsup:":
        rcount = reaction.count

not as efficient, but would work.

slate swan
#

I hope so

#

It worked

brittle ingot
#

yay!

slate swan
#

Thank you

brittle ingot
#

np

hollow agate
#
@client.command()
async def mute(ctx, member: discord.Member, time, *, reason=None):
    if member is None:
        await ctx.reply('You must mention someone to mute!')
        return
    if reason is None:
        await ctx.reply('Please state a reason!')
        return
    if ctx.message.author.guild_permissions.administrator:
        if time is None:``` Very interesting question. Is it possible that I can allow it to where the time is none at the bottom? It insists there is a time and it only insists if there's the `if ctx.message.author.guild_permissions.administrator:` that I need which is bizzare.
neon oyster
#

no roast plz py def check(message): return message.author.id == ctx.author and ( message.channel.id == channel.id or isinstance(message.channel, discord.DMChannel) )This fucktion works in dm but not with channel

neon oyster
brittle ingot
rare saddle
#

How to make an error handler - if the bot lacks rights?

neon oyster
#

rights?

hollow agate
#

I'm not sure why it works without the permission check...

brittle ingot
#

ok so you can do:

time: int=None

I believe?

slate swan
#

Hello! I am using this line meant to clear discord message cache: bot.clear() but for whatever reason it starts to return this error after executing:

hollow agate
#

This is all super confusing

#

So a normal mute command would be .mute @hollow agate 3d Test

brittle ingot
#

yeah, im trying to think of the best way to do it, i have a way but its way too ridiculous to even propose, it involved checks and way too much work for something that simple.

hollow agate
#

Would you mind showing me it, it might give me a few ideas?

brittle ingot
#

so instead of checking if time is none you would check if time[-1] is one of the accepted characters for your converter (i.e: s, m, h, d)

if time[-1] in ['s', 'm', 'h', 'd']:
    ...

if it isnt one of the accepted characters then combine time + reason to get full reason. Otherwise the first word will always be omitted from the reason. The issue with that is if someone does for instance "word used in derrogatory way" as the reason it will trigger that check thus causing an error. I suppose you could get around this by trying to convert the first portion of the "time" string to an int and handling if that errors 🤷‍♂️

hollow agate
#

What is [-1]?

brittle ingot
#

its an index to the string. You can index string like lists. its saying we only want the last letter of the value of time. so if you do 30d it will return d

#

sorry for late response im working on a web server 😂

kindred epoch
#
something1 = await self.client.pg_db.fetch("SELECT card_name,card_id,card_url,card_rarity,card_set_name FROM cardsclone WHERE card_rarity = 'Rare Holo' AND card_set_name = 'Base'")
            print(something1)
            something3 = random.choice(something1)
``` ok so im fetching these things from my db and its 100% not empty, but whenever it tries to pick a random thing from the list it says "list index is out of range", anyone know why?
brittle ingot
#

what is something1 printing?

kindred epoch
#

it does not print

#

thats the problem

#

when i fetch it myself it returns something

#

but whenever i try to use the command it just does not print

brittle ingot
#

there is more code yes? can we see that code that the error is referring to, including the above code aswell.

#

if you need more space you can use

#

!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.pythondiscord.com/

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

kindred epoch
#
checkbuttonornot = await self.client.pg_db.fetchrow("SELECT togglebutton FROM pokesets WHERE user_id = $1",ctx.author.id)
        if checkbuttonornot['togglebutton'] == 2:
            set = ["Base","Jungle","Fossil","Base Set 2","Team Rocket"]
            commonrarity = ['Common','Uncommon','Rare']
            channel = self.client.get_channel(862538736780967936)
            somethingg = random.randint(1,100)
            print(somethingg)
            if somethingg in range(1,99):
                randomrarity = f'{random.choice(commonrarity)}'
                randomset = f'{random.choice(set)}'
            elif somethingg == 100:
                randomrarity = 'Rare Holo'
                randomset = f'{random.choice(set)}'
            elif somethingg == 99:
                randomrarity = 'Rare Holo'
                randomset = f'Base'
            something1 = await self.client.pg_db.fetch("SELECT card_name,card_id,card_url,card_rarity,card_set_name FROM cardsclone WHERE card_rarity = 'Rare Holo' AND card_set_name = 'Base'")
            print(something1)
            something3 = random.choice(something1)
#

thats all above it

#

under it is not needed

pine lava
#
        if ctx.channel.category == category:
            pass
        elif ctx.channel.id != 907047948595105802:
            e = discord.Embed(title="Command Unaccessible", description=f"You can only use this command in [#907047948595105802](/guild/267624335836053506/channel/907047948595105802/)!", color=0xFFD700)
            await ctx.message.delete()
            await ctx.send(embed=e)
            return``` how would i make it so it skips over the second if statement if the channel is in the category?
kindred epoch
#

it wont let me copy paste that for some reason

slate swan
#

trying to retrieve the image URL of the screenshot someone deleted

@bot.event
async def on_message_delete(message):
    print(message.attachment.url)```
says its not a valid attr, any ideas? i used message.attachments but that returned a string
brittle ingot
#

!d discord.Message.attachments

unkempt canyonBOT
visual island
unkempt canyonBOT
#

@visual island :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 |   File "/usr/local/lib/python3.10/random.py", line 378, in choice
004 |     return seq[self._randbelow(len(seq))]
005 | IndexError: list index out of range
kindred epoch
#

and?

visual island
#

your iterable is empty

brittle ingot
# kindred epoch this is the error

alr, im still looking at your code. right now only thing i can think of is are you sure its "fetch" and not "fetch_many" or something as far as the db is called?

kindred epoch
#

yes

#

its postgres so its fetch

brittle ingot
#

alr, not too familiar with postgres.

kindred epoch
kindred epoch
brittle ingot
#

tbh i would ask in #databases they may know more about how to help.

kindred epoch
#

@visual island

kindred epoch
#

ok nvm

slate swan
#

does anyone have a list of discord emotes in :emote: format

#

PLEASE

slate swan
#

no like 😄 emotes

#

not custom

brittle ingot
#

you mean default emojis

slate swan
#

i need a list of them in :format:

#

\😄

#

?

#

well if i did that

#

no i mean like default emotes in :format:

trim fulcrum
#

im trying to put a directory

#

how wold i do that

slate swan
slate swan
#

do \:smile:

brittle ingot
#

Anyways, you can find them on a unicode emoji directory 😄 as well.

slate swan
#

Exactly

brittle ingot
#

||There is an emoji pack for python on pypi||

trim fulcrum
#

im trying to put a directory
how wold i do that

brittle ingot
trim fulcrum
brittle ingot
#

and that is an existing directory?

trim fulcrum
#

yes

brittle ingot
#

is it within your bots directory? so like the folder is in the same folder as your main.py file?

trim fulcrum
#

no

#

its in another one

slate swan
#

is the ids folder in same directory as your bot

trim fulcrum
#

no

#

only fteched.txt is in ids folder

slate swan
#

ok then why would you put root/ids/fetched.txt

#

do the actual location

brittle ingot
#

./file = current directory
../file = directory before current directory
append ../ until you get back to the directory you need for ids folder.
EDIT: how it works in JS anyways.

trim fulcrum
slate swan
#

that is current directory

trim fulcrum
#

ik

slate swan
#

if its not in the current directory that is wrong

brittle ingot
#

that would be the directory your bots mainfile is in.

#

you will want to do: ../ids/fetched.txt if you are going back one further.

trim fulcrum
brittle ingot
#

Otherwise idk, cause i can't see your directory make up.

#

if its in the ids folder you will need to add that as well. ./ids/fetched.txt but try: ../ids/fetched.txt first

slate swan
#

you can copy it

brittle ingot
#

sheeeeeeesh 😅

slate swan
#

how can i return the url on its own

trim fulcrum
#

@brittle ingot

brittle ingot
trim fulcrum
#

no

brittle ingot
#

well i need to see where you are in relation to the file 😄

trim fulcrum
brittle ingot
slate swan
trim fulcrum
slate swan
slate swan
trim fulcrum
slate swan
#

whos saage

trim fulcrum
#

lmfao ok bud

slate swan
#

k den

brittle ingot
#

if message.attachments returns a list you index it like:
let attachment = message.attachments[0].url (this is assuming you know there is only one attachment for the message.)

slate swan
#

nawl bro jus exposed your secret

#

make a check

slate swan
brittle ingot
#

make a bot.check() and check against a list of accepted users.

brittle ingot
#

almost exclusive to lists and extracting data from a list or string.

slate swan
#
    @commands.has_permissions(manage_roles)
NameError: name 'manage_roles' is not defined```what-
#

neverminddd

#

manage_roles=True

regal shell
#

Ok so I’ve switched over to vsc but it’s saying no module name discord when I try to import discord

slate swan
slate swan
#

if im right

if ctx.author == ctx.guild.owner```
is the same as
```py
if ctx.author is ctx.guild.owner``` 
right?
#

Indeed

lyric moat
#

why this gives an error

summer lagoon
#

Does someone know how to solve it? When I was using that same bot in other server it worked very well.

slate swan
#

2fa?

#

show the command?

summer lagoon
#
@client.command()
async def add_message(ctx):
  await ctx.message.delete()
  caller = ctx.author.id
  print('Enviando imagem...')
  n_vc_channel_id = returnChannelIdByBotMaterId(ctx.author.id, 'bot_master')
  if caller == channels_ids[n_vc_channel_id]['bot_master']:
    with open('src/calax_banner.png', 'rb') as f:
      picture = discord.File(f)

    message = await ctx.send(file=picture)
    await message.add_reaction("👍")  
summer lagoon
slate swan
#

strange

vocal plover
#

if not, your bot cant do moderation actions in servers with the 2fa requirement enabled

#

such as delete messages

regal shell
#

Why does it say no module named discord when I try to import discord

summer lagoon
regal shell
#

I’ve tried that says no command “pip”

brave flint
#

hello i got an error has_role()got an unexpected keyword argument "administrator" from :

    @commands.has_role(administrator = True, ban_members=True)```
did i mistype?, i use cogs too
slate swan
#

if they have admin then they have ban_members

#

commands is also lowercase i think

vocal plover
#

also has_role takes in either role names or ids, not keyword args for permissions

slate swan
#

@commands.has_permissions also

regal shell
brave flint
slate swan
#

linux

brave flint
#

just the ban_member?

vocal plover
#

pip3 for linux

slate swan
regal shell
#

“-bash: pip: command bot found”

#

Is what it said back

slate swan
#

pip3

#

pip3 install discord

regal shell
#

It’s doing something lmfao

pliant gulch
#

Have you got python installed?

slate swan
#

then it worked

pliant gulch
#

Try doing python -m pip or pip3

slate swan
#

i thi nk

regal shell
#

I have python installed through vsc do I need to do it through Linux terminal aswell?

slate swan
#

no

regal shell
#

I’ve only ever coded on replit so never had to download or install anything

brave flint
#

i think u need to install python and add it to path

slate swan
#

you can't on linux

#

i don't think

brave flint
#

oh sorry

slate swan
#

i could be wrong

pliant gulch
#

The python on visual studio code is a language pack, its for stuff like LSP stuff etc

regal shell
pliant gulch
#

You need to install python on your own computer

slate swan
brave flint
slate swan
#

you should be good now

summer lagoon
slate swan
#

just restart vscode @

vocal plover
#

Happy to help :P

regal shell
regal shell
slate swan
#

if your bots online

#

!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.
regal shell
#

Yeah no it’s not lol

slate swan
#

problem with your code

regal shell
#

Wait

slate swan
#

take a ss of your vscode window

regal shell
#

I figured it out 😂

slate swan
#

ok

regal shell
#

Thanks bro

#

How do I turn it off lmfao 🤣

slate swan
#

click the big red square

regal shell
#

Ah ok

slate swan
regal shell
#

Yeah it’s definitely something different

#

Now time to figure out why my unban command hates me

slate swan
#

!d discord.Member.unban

unkempt canyonBOT
#

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

Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
regal shell
#

Yeah it’s something with indent but it’s being stupid

#

Works when out of cog

slate swan
#

indentation = easy fix

regal shell
#

Help me lmfao? I suck at cogs

slate swan
#

send ss of code

#

it's easier to see the indentation error thru a ss in my o

regal shell
#

If I can remember how to ss in chrome book 💀

slate swan
#

the window looking thing

#
  • ctrl
ornate glade
#

I was wondering if there was a way to take image user input? Specifically, make the bot copy the link of the image and then send it into an embed? Here's my code so far:

4th field

def check4(msg4):
return msg4.author.id == member.id and msg4.channel == channel

await channel.send("Any screenshots? If you do, paste in a link to the screenshot (i.e. imgur.) If you don't type None")

try:
msg4 = await client.wait_for('message', check=check4, timeout=120)

except asyncio.TimeoutError:
await channel.send("You didn't reply in time.")
guild = member.guild
await channel.set_permissions(member, send_messages = False)

role = discord.utils.get(guild.roles, name='InReports')
await member.remove_roles(role)
sick birch
regal shell
#

Ik it’s on repl just easier to see

ornate glade
slate swan
#

put the least await inline with the first

#

ctx.channel is also = to just ctx so you could also do

ctx.send

regal shell
#

A bunch more red pops up lemme run to see the actual error

slate swan
#

but

sick birch
#

but i see what you mean, just to set the record straight

slate swan
#

yes i was just about to correct myself but i started eating 😹😹

regal shell
#

Says await is outside function

slate swan
#

put it inside the async function

regal shell
#

It is I think?

slate swan
#

click space on the for line

regal shell
#

Ok red went away new red showed up

slate swan
#

then it wi be an indent error then it's easy to fix

#

i think

regal shell
#

Yes it is indent error lemme take new pic

slate swan
#

honestly you should revamp the whole command your indentation is pretty 💩

regal shell
#

I indent does not match any outer indentuon level

slate swan
#

member_name aligned with banned_users

regal shell
#

Was it really that easy lmfao

slate swan
#

yes

regal shell
#

Ok let’s see what happens when I put it in vsc

#

Yeahhhh a bunch of red I hate this lol

brave flint
#

um bro

#
    @commands.has_role("Giveaway Host")
    async def giveaway(self, ctx):```
#

i test it with Giveaway Host role and it doesnt show, but reroll cmd showed

slate swan
regal shell
#

Yes lmfao

brave flint
#

for me

slate swan
brave flint
slate swan
# regal shell
for ban_entry in banned_users:
user = ...``` wrong indentation here
#

also dont use lucas unban , its complex and makes an extra api call , just typehint member to discord.User , and do ctx.guild.unban(member)

regal shell
#

I’ve changed the unban command just saying none of my commands have attributes

#

Ima just quit for today I transferred my code over and it’s pissing me off now lmfao

maiden fable
slate swan
maiden fable
#

I think it tries to convert, but if it doesn't work, only the ID is there with us. The raw ID without any conversion

slate swan
maiden fable
#

Oh hmm

#

Didn't know that

slate swan
#

How do I make it so that my bot reads for a specific response only after it has sent a certain message

vale wing
#

Using wait_for

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
main onyx
#

@client.command gets an error

sick birch
slate swan
#
@bot.command(aliases=["userinfo", "who", "whois"])
@blacklist_check()
async def ui(ctx, member : Union[discord.Member, discord.User]=None):
    if member == None:
        member = ctx.author
    user = await bot.fetch_user(member.id)
        # ---------------------------- #
        # ---------------------------- #

    br = "![bug_hunter](https://cdn.discordapp.com/emojis/910676656602103838.webp?size=128 "bug_hunter")"
    bot_owner = "![bot_owner](https://cdn.discordapp.com/emojis/910676656648237106.webp?size=128 "bot_owner")"
    bot_staff = "![bot_staff](https://cdn.discordapp.com/emojis/910676656602095667.webp?size=128 "bot_staff")"
    supporter = "![supporter](https://cdn.discordapp.com/emojis/910676656539185173.webp?size=128 "supporter")"
    bot_badges = "none"
        
    if member.id == 898420656725704705:
        bot_badges = f'{br}, {bot_owner}, {bot_staff}, {supporter}'
        # ---------------------------- #
         # ---------------------------- #

    date_format = "%a, %b %d, %Y, %R %p"
    embed = discord.Embed(title=f"{member}", color=color)
    embed.add_field(name="dates", value=f"**registered**: {member.created_at.strftime(date_format)} \n**joined**: {member.joined_at.strftime(date_format)}", inline=False)
    role_string = ' '.join([r.mention for r in member.roles][1:])
    embed.add_field(name="roles", value=role_string, inline=False)
    embed.add_field(name="userid", value=f"`{member.id}`", inline=False)
    embed.add_field(name=f"bot badges", value=f"{bot_badges}",inline=True)
    embed.set_thumbnail(url=f"{member.avatar_url}")
    await ctx.send(embed=embed)```

Ignoring exception in command ui:
Traceback (most recent call last):
File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\misery\Desktop\alone\bot\main.py", line 306, in ui await ctx.send(embed=embed)
File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_components\dpy_overrides.py", line 350, in send_override
return await send(channel, *args, **kwargs)
File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_components\dpy_overrides.py", line 325, in send
data = await state.http.send_message(
File "C:\Users\misery\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form BodyIn embeds.0.fields.1.value: This field is required

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

Traceback (most recent call last):
File "C:\Users\misery\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\misery\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\misery\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: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.1.value: This field is required```

#

^^^ ping if respond

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 | SyntaxError: 'await' outside function
slate swan
#

!cleanup

#

ok

visual island
slate swan
#

yeah figured that out

#

help plz

sullen shoal
#

you gotta typehint them

#

discord.Member, discord.Role

brave flint
#

so i made a line to prevent using cmd from different voice channel like:
if ctx.author.voice.channel == ctx.voice_client.channel:
but sometime it shown AttributeError: 'NoneType' object has no attribute 'channel' on that line

slate swan
full valley
#

How would I edit a message sent in another command?

sullen shoal
#

fetch it

full valley
#

Not sure how to do that

brave flint
full valley
brave flint
#

idk

sullen shoal
#

you can save the message object then just edit it there

full valley
#

Where would I save it

sullen shoal
#

put the commands in a cog then save it as an attribute of the cog subclass

full valley
#

Right, but im not using cogs or classes

#

so :/

sullen shoal
#

i would ask why not

#

otherwise you may set them to bot

brave flint
sullen shoal
#

like, bot.hello = "one"

#

then bot.hello will return "one"

brave flint
#

myxi can u help me with my problem?

sullen shoal
#

which problem

sullen shoal
#

not sure never worked with voice stuff

#

so you dont want your users to use commands in other voice channels

upbeat otter
brave flint
#

so its cant fixed or how mybe?

slate swan
#

if i want to give the bot a role what would my code look like?

upbeat otter
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

upbeat otter
#

,-,

brave flint
#

chunk?

sullen shoal
unkempt canyonBOT
#

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

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

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

thnx m8

upbeat otter
slate swan
#

i already got that imported i was just confused on what the code looked like

upbeat otter
#

!d discord.utils.get

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
#

alright

upbeat otter
sullen shoal
#

i think guild.me wilk return th me Member object of your bot

brave flint
#

i tried to dc it and it show

upbeat otter
#

sad

brave flint
#

lol

#

google it then

sullen shoal
unkempt canyonBOT
#

property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
slate swan
#

what would be the best way to do a server stats channel type thing

sullen shoal
#

idk show screenshot

slate swan
#

k

#

like those bottom 3

#

Just make a task that will run every x minutes and update everything

#

but would that method work for multi server

#

Yes, if you have a database where to store the channel IDs.

#

k

boreal ravine
#

Very "k"

sullen shoal
#

Potassium

gaunt ice
#

hm

slate swan
#

can someone help me make a bot that would ban all users with a keyword i put? our server was raided and dont wanna ban manually

sullen shoal
#

!d discord.Guild.members

unkempt canyonBOT
#

property members: List[discord.member.Member]```
A list of members that belong to this guild.
sullen shoal
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
sullen shoal
#

wdym

slate swan
#

how can I get a guilds id in a tasks.loop

#

I cant hardcode it in

humble dune
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '>=' not supported between instances of 'int' and 'str'

high pollen
#

how do i get the url of the member in on_member_join(self, member) it is in a cog?

humble dune
high pollen
#

both should be int or str

#

u can use int(x) >= int(y)

humble dune
#

this is the line showing

high pollen
#

the money over there is a variable?

humble dune
high pollen
humble dune
humble dune
#

as i use pandas module

high pollen
#

then try printing type(int(data.loc[str(id),"money"])

#

and type(money)

#

to check if both are int

humble dune
#

thx

high pollen
#

np :)

#

how do i get the url of the member in on_member_join(self, member) it is in a cog?

high pollen
boreal ravine
#

What are you saying then

high pollen
#

member is just the username with #xxxx

boreal ravine
#

yes

high pollen
#

i need the url of their pfp

boreal ravine
#

what URL though

boreal ravine
unkempt canyonBOT
#

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

then

boreal ravine
#

you already have the member instance

#

just the the avatar attribute on it

high pollen
#

ok

#

testing

slate swan
#

so i have a command for a giveaway but it only works in seconds for some reason

#

i cant seem to figure out how to change it

boreal ravine
#

Me either

slate swan
#

gimme a second to get the code lol

humble dune
#

AND INT

high pollen
boreal ravine
high pollen
#

money or the other one

slate swan
humble dune
boreal ravine
slate swan
#

the embed already has enough latency

boreal ravine
#

embed's literally cant slow ur bot down unless its big 🤨

high pollen
slate swan
#

see the problem is that its meant to run in one instance but in the hundreds

boreal ravine
#

its running a 100 instances? or is it getting "100" latency

slate swan
#

100 embeds with the same timer

humble dune
boreal ravine
high pollen
high pollen
slate swan
#

this might be janky but it might work

humble dune
#

pandas is a very rare using module

sullen shoal
#

every second skid uses it nowadays

full valley
#

Is there a way to switch the bot from working per guild to let channel in a guild

sullen shoal
#

idk what you are asking for

full valley
#

It’s kind of hard to explain, so like each channel in a server acts like a different guild, instead of the bot working for the entire guild

sullen shoal
#

looks like some made up idea that you have to work on by your own

boreal ravine
full valley
#

Nah It’s from a bot that i’ve seen

#

Hold on I’ll give you some more context

sullen shoal
#

what does act mean in this case

#

like what special will each channel have

full valley
#

So I'm making a 6 mans bot, where players can queue up, and then it sorts them out into random teams and things, then they report a win/loss and the information is stored to my mongo db.

There is another 6 mans bot that allows you to change the bot usage to per channel or per guild.

Per channel allows you to have different queues and a different leaderboard in each channel. So basically acting like each channel is a seperate guild. If you change this to per guild, all the channels you run the bot in will link to the same queue and leaderboard.

#

does that make sense

sullen shoal
#

it makes sense but i think its all about, on_message event and a database of channel id to identify these stuff

#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
steep estuary
#

what are server member intents ?

#

and for what it is used ?

sullen shoal
#

it will be called on each message your bot could see, you may use discord.Message.channel.id to identify different channels

full valley
# unkempt canyon

hmm just not sure how I would adapt it to have a command that changes it between per channel/guild

sullen shoal
#

its all about the database,
like i cant help you with building your logic, you have to do that by your own.
discord.TextChannel.id, discord.Member.id, discord.Guild.id will help you with what i have understood

full valley
#

alright ill see what I can do, thanks for your help

hexed spoke
#

does anyone know how to code a discord bot

#

I've tried learning on youtube, I am learning but not the right way.

full valley
#

Do you know how to code in python?

hexed spoke
#

yes

sullen shoal
hexed spoke
#

the github

#

says 404

sullen shoal
#

there

#

youtube tutorials are always trash please dont watch them

#

a good library will always have docs and examples

#

those are enough if you know what you are doing

hexed spoke
#

what do you mean by libraries

sullen shoal
hexed spoke
hexed spoke
#

I might be back

sullen shoal
#

like some people might do something like

x = 'hello'
y = 'xhello'
y[0:len(x)] == x

to check if something startswith something not knowing,
a method startswith for the object str exists

boreal ravine
sullen shoal
#

why are you asking this in python programming language discord server

boreal ravine
sullen shoal
#

read the conversation

boreal ravine
#

ah

sullen shoal
#

we will help with getting it working into your python project but you gotta know the source

#

like if you want to read from a file, we will help with reading but you have to find the path to the file

full valley
#

What are these for and do I need to use them in order to verify the bot

full valley
#

I know what they are

#

but are they needed to verify the bot

sullen shoal
#

read the bold text, once your bot reaches 100 servers, you will have to verify your bot

full valley
#

so you dont need them

sullen shoal
#

you have to turn them on to do specific task

#

but you dont need to verify untill it reaches 100 servers

hexed spoke
high pollen
#

How do I get the id of a channel I created?

#

channel = await guild.create_text_channel(f'{name}', overwrites=overwrites) I want the id of channel

gaunt herald
#

How to use heroku for discord bot s?

#

Can someone tell me? Pls

brave flint
#
    @commands.has_role(Giveaway_Host=True)```
why it give error :
```has_role() got an unexpected keyword argument "Giveaway_Host"```
gaunt herald
brave flint
sullen shoal
unkempt canyonBOT
high pollen
#

so i do channel.id?

sullen shoal
#

think and try

high pollen
#

yup

#

got it ty

sullen shoal
#

before asking for help, check the docs and see the return type and stuff and try your best to not ask for help. thats how you learn

sullen shoal
hexed spoke
#

thank you

sullen shoal
#

👍

maiden fable
unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
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 the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, 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 [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") 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")
sullen shoal
#

it didnt show the content i wanted to show so i gave the link

maiden fable
#

Ah, okay. Cool

sullen shoal
#

Parameters

    item (Union[int, str]) – The name or ID of the role to check.
full valley
#

I've got a queue command:

#!q command -> Puts players into queue
@bot.command(name="queue", aliases=["q"], description="Join the queue")
@commands.check(is_issuer_in_game)
async def queue(ctx):
    if ctx.channel.id in allowed_channels:
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        game_id = ggid["game_id"]
        qsize = ggid["qsize"]
        pid = ctx.author.id
        pmention = ctx.author.mention

        if pmention not in playerqueue and len(lobby) < qsize:
            playerqueue.append(pmention)
            lobby.append(pid)
            info = pstats.find_one({"id": pid})
            if info is None:
                newuser = {"id": pid, "Wins": 0, "Losses": 0, "MMR": 1600, "Rank": "C"}
                pstats.insert_one(newuser)
            embed = discord.Embed(
                title=f"**{len(playerqueue)} of {qsize} players are in the queue**",
                description=str(ctx.author.mention) + " has joined!", color=0xE74C3C)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)

        if len(lobby) == qsize:
            games[game_id] = lobby.copy()
            lobby.clear()
            playerqueue.clear()
            game_id += 1
            settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
            embed = discord.Embed(
                title=f"**The queue reached {qsize} players**",
                description="Voting is now underway!",
                color=0xE74C3C)
            embed.add_field(name="Vote for:", value="Captains", inline=True)
            embed.add_field(name="\u200b", value="Balanced", inline=True)
            embed.add_field(name="\u200b", value="Random", inline=True)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)
            await ctx.channel.send(
                "\u200b",
                components=[[
                    Button(style=ButtonStyle.red, label="Captains"),
                    Button(style=ButtonStyle.blue, label="Balanced"),
                    Button(style=ButtonStyle.green, label="Random")]])
            while True:
                res = await bot.wait_for("button_click")
                if res.component.label == "Captains":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))
                if res.component.label == "Balanced":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))
                if res.component.label == "Random":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))

How can I delete the buttons mentioned above,
after it runs the r command:

#!r command -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def r(ctx):
    if ctx.channel.id in allowed_channels: #and ctx.author.id in games.values():
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        qsize = ggid["qsize"]
        game_id = ggid["game_id"]
        set_aid.add(ctx.author.id)
        if len(set_aid) == qsize/2:
            set_aid.clear()
            **Delete buttons**
            embed = discord.Embed(description="Random teams have been chosen",
                                  color=0xE74C3C)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix",
                             icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)
brave flint
#

is there any docs for not loaded commands?

#

i maded giveaway commands but it doesnt show on help

#

not showing any error tho

brave flint
#

it doesnt give any error and i arl fixed has_role error

full valley
#

its not help isnt it

#

its description=""

brave flint
#

it can be help=""too

#

my other code use help="" and no problem

#

the reroll use help="" too

shadow wraith
#

just use description="" and see what happens

boreal ravine
brave flint
boreal ravine
brave flint
boreal ravine
#

!d discord.ext.commands.Command.help

unkempt canyonBOT
boreal ravine
#

hm

boreal ravine
brave flint
#

well it doesnt reply anything too when i used it

brave flint
#

i like searching for like 4 hours with another error

boreal ravine
#

hm

brave flint
#

and only this one still exits

sullen shoal
#

help is for the long description of a command. even if it works, its not meant for short description. use the description parameter, it may not fix the problem but always use the right parameter

brave flint
#

okie ill try, maybe it can fixit too

sullen shoal
#

from all commands

brave flint
brave flint
#

Giveaways:
Reroll
Moderator:

sullen shoal
#

is the cog long

brave flint
#

and the giveaway command still not load

brave flint
sullen shoal
#

use a text bin and give me the link

#

and show me the code to load cogs

brave flint
#

all of my code or wht

sullen shoal
#

just cog thats not loading

brave flint
#

the cogs load but not the command

sullen shoal
#

how many commands does the cog have

#

if there are other commands, are they working?

brave flint
sullen shoal
#

the command looks okay, i think some other part of the cog is causing it

sullen shoal
#
@commands.command(name="Giveaway", help="Made giveaway event")
    @commands.has_role("Giveaways Host")
    async def giveaway(self, ctx):```
is it really like that or it happened during pasting it?
#
@commands.command(name="Giveaway", help="Made giveaway event")
@commands.has_role("Giveaways Host")
async def giveaway(self, ctx):

it is supposed to be like this

full valley
#

I'm struggling on updating a past message sent by my bot

upbeat otter
full valley
#

how can I get the id of a bot msg?

full valley
brave flint
upbeat otter
sullen shoal
sullen shoal
brave flint
#

there

brave flint
sullen shoal
#

two functions with the same name

#

you have to name them differently

upbeat otter
# brave flint

why're you using format and you have the same function name twice

brave flint
#

wut?

sullen shoal
#

you cannot declare two functions with the same name

upbeat otter
#

.

sullen shoal
#

the second command is working because, first one has been replaced with it

brave flint
#

class and add cog?

#

oh how i so blind

#

i forget to rename the reroll one

sullen shoal
#

commands are no more but functions.

def foo(): print('one')
def foo(): print('two')
foo() # will print 'two'```
upbeat otter
#

change one of their names @brave flint

brave flint
upbeat otter
#

@brave flint you have a huge fault in your function

#

you have declared the name reroll in commands.command() and declared the name giveaway while making the function

brave flint
upbeat otter
#

in the first one

brave flint
#

well my code already working now

#

tq for both of you guys

sullen shoal
#

if you dont pass the name parameter, discord.py uses the function name giveaway.__name__, but if you pass it, it will use that instead

upbeat otter
#

why is this saying: Bot has no attribute 'fetch_message'

#

the docs show fetch_message but it doesnt work

sullen shoal
#

there are different ways to fetch a message, none of them includes Bot.fetch_message

sullen shoal
#

what you did is not correct

upbeat otter
sullen shoal
#

have a look at the link I sent, it depends on where you are trying to fetch it

#

and why

upbeat otter
#

All I need to fetch is the message of my bot using an ID

sullen shoal
#

show me more of the code

upbeat otter
#

thats all of it

sullen shoal
#

more

upbeat otter
#
try:
      msg = await client.fetch_message(ID)
      print(msg)
    except Exception as e:
      print(e)
sullen shoal
#

the entire command

upbeat otter
sullen shoal
#

!d discord.ext.commands.Context.fetch_message

unkempt canyonBOT
#

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

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

Context is the first argument of every command

upbeat otter
sullen shoal
#

think

upbeat otter
#

idk, am confused

sullen shoal
#

discord.ext.commands.Context.fetch_message

#

Context is the first argument of every command

upbeat otter
glass rock
#

is it possible to update a bots code without restartng it

upbeat otter
boreal ravine
unkempt canyonBOT
#

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

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

it will fetch any Message but you cant edit them

upbeat otter
boreal ravine
glass rock
sullen shoal
#

or maybe it doesnt and only could fetch messages from the client

boreal ravine
glass rock
sullen shoal
#

keep in mind, this will cost an API request, meaning if 50 people use it under one second, your bot will be rate limited

boreal ravine
upbeat otter
#

@boreal ravine ```
msg = discord.TextChannel.fetch_message(ID)
print(msg)

upbeat otter
boreal ravine
#

your code

upbeat otter
#

yes

glass rock
boreal ravine
# upbeat otter yes
discord.TextChannel.fetch_message()

^^^^^   ^^^^^^^^       ^^^^^^
class    class          method
``` yeah just get the instance of it don't use the class
boreal ravine
#

🤨

sullen shoal
#

it shouldnt work with the base class anyway

upbeat otter
#

nvm

glass rock
#

😦

boreal ravine
#

wait locals vars restart too if you reload them 🤨

glass rock
sullen shoal
#

then what do you think a database is for

upbeat otter
#

@sullen shoal thanks, I understood now, I'm quite dumb 🥲

sullen shoal
#

👍

#

you can fetch the Message from discord.Member to edit them I think. (only if the Member is the client)

boreal ravine
#

self botting

sullen shoal
#

unless theyre doing stuff like editing a message with stats, yes

glass rock
#

btw how much data does hosting a bot use per hour? A rough estimate would be appreciated

boreal ravine
#

If its local it doesn't use data

glass rock
#

pog

#

how tho the bot needs to send messages and stuff right?

sullen shoal
#

wdym by data

#

internet usage?

glass rock
#

internet bytes

boreal ravine
glass rock
sullen shoal
#

the only way to know would be to calculate it yourself.

#

each request ranges from 2 to any amount in KB

glass rock
boreal ravine
glass rock
#

as long as it isnt >200Mb/hr i should be good

boreal ravine
#

ig

glass rock
#

sorry im noob

boreal ravine
glass rock
#

wow

sullen shoal
#

my guess is that discord.py starts a web server where requests from discord comes when user sends a message or stuff
otherwise i think discord.py constantly sends requests to some endpoints to see if theres any new request or smth. the only way to know what happens would be to check the gateway

maiden fable
#

The websocket (gateway) sends the events automatically and dpy receives them with aiohttp

#

Also it pings the gateway every x seconds so that discord knows that the bot is still on

sullen shoal
#

i see

maiden fable
#

Yups, I have myself successfully made a private wrapper for a discord like API, so I can surely tell u all these basic things haha

sullen shoal
#

oh yeah i heard you're making an api wrapper for smth called revolt

#

good luck

maiden fable
#

Yups, a private one for only my bot (I have successfully completed it)

sullen shoal
#

great

vocal plover
boreal ravine
#

well yeah

static gazelle
boreal ravine
#

wut

static gazelle
#

how you do it?*

boreal ravine
#

idk

slate swan
slate swan
#

Can someone tell me how I can make this picute rounded?

#

It's a welcoming message

sullen shoal
#

idk where i had the code

slate swan
sullen shoal
#

its very old btw so the code i wrote is little dumb let me check tho

slate swan
#

As long as it works, that's completely fine xd

sullen shoal
#

ugh i deleted it some time ago

slate swan
#

ohh mann :/

sullen shoal
#
import Image, ImageDraw

def add_corners(im, rad):
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', im.size, 255)
    w, h = im.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
    im.putalpha(alpha)
    return im

im = Image.open('tiger.jpg')
im = add_corners(im, 100)
im.save('tiger.png')```
#

try this

boreal ravine
#

what the spoonfeed

sullen shoal
#

just some copy pasta

slate swan
#

thx

slate swan
#

I used numpy to make my corners rounded

sullen shoal
#

i thought numpy is some math kinda module

slate swan
#

Now it's kinda weird.. On Discord it looks like this

#

On web like this

sullen shoal
#

looks like youre saving it as jpg

slate swan
#

nope

sullen shoal
#

show code

slate swan
#

png

sullen shoal
#

entire command

unkempt canyonBOT
#

utils/pillow/rank_card.py lines 59 to 70

av = Image.open('avatar.png')
av = av.resize((250, 250))
h, w = av.size
npImage = np.array(av)
new_img = Image.new('L', av.size, 0)
draw = ImageDraw.Draw(new_img)
draw.pieslice([0, 0, h, w], 0, 360, fill=255)
np_new = np.array(new_img)
npImage = np.dstack((npImage, np_new))
final_img = Image.fromarray(npImage)
final_img.thumbnail((250, 250))
final_img.save('avatar.png')```
slate swan
#
    filename = "welcomefile.png"

    background = Image.open("welcome.png")

    asset = member.avatar_url_as(size=256)
    data = BytesIO(await asset.read())

    pfp = Image.open(data).convert("RGBA")
    pfp = pfp.resize((256,256))

    pfp = add_corners(pfp, 100)

    background.paste(pfp, (385,130))
    background.save(filename)
sullen shoal
#

i mean mine does too ik

slate swan
#

That's why it's ran in the executor

sullen shoal
#

oh

boreal ravine
sullen shoal
#

but the thing is it could be better

slate swan
boreal ravine
slate swan
#

Lyt

#

❤️

#

hahahaah

sullen shoal
#
async def image_helper(user, asset:str, size:tuple, pos:tuple):
    _asset = Image.open(f'cogs/assets/{asset}')
    avatar = await user.avatar_url_as(size=512, format = 'jpg').read()
    avatar = Image.open(io.BytesIO(avatar))
    avatar = avatar.resize(size)
    _asset.paste(avatar, pos)
    buffer = io.BytesIO()
    _asset.save(buffer,'PNG')
    buffer.seek(0)
    return buffer```
```py
    @commands.command()
    async def wanted(self, ctx, user: discord.User = None):
        file = await image_helper((user or ctx.author), 'wanted.jpg', (300,300), (28, 103))
        await ctx.send(file = discord.File(fp = file, filename = 'kreklie_wanted_image.jpg'))```
#

very old code so some stuff is very dumb

#

also it blocks the script

#

kinda

slate swan
#

d! events

sullen shoal
#

#bot-commands

slate swan
sullen shoal
#

it doesnt do what you want

slate swan
#

oh

#

I‘ll search it up and try to find a good solution. I‘ll let u know if i was successful or not

#
    async def ban(self,ctx,  user: discord.Member , * , reason=None):
        if not self.check(ctx,user): return await ctx.send(embed=discord.Embed(title='oh no an error occured',description="cant ban yourself or anyone higher than you",color=0x992d22))
        if ctx.author.id == user.id : return await ctx.send(embed=discord.Embed(title='oh no an error occured',description="cant mute yourself or anyone higher than you",color=0x992d22))
        embed = discord.Embed(title=f'{user.name} got banned from {ctx.guild}',description=f' Reason : {reason}')
        embed.set_thumbnail(url=ctx.guild.icon_url)
        embed.set_footer(text=f'executed by {ctx.author}',icon_url=ctx.author.avatar_url)
        try:
            await user.send(embed=discord.Embed(title=f'you got banned from {ctx.guild}',description=f'Reason : {reason} '))
        except Forbidden:
            await ctx.send("they have their dms close. I couldn’t DM :dead:")
        finally:
            await user.ban(reason=reason)
            await ctx.send(embed=embed)```
upbeat otter
upbeat otter
slate swan
#

then your bot doesn't have perms to ban

upbeat otter
#

yep

slate swan
#

wawait

#

it worked when i gave the bot admin

#

but the thing is , when i added the bot i selected admin

#

also why does it purge the user after they are banned

boreal ravine
#

u said it had admin though

slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
slate swan
#

simply have the kwarg delete_message_days to 0

slate swan
#

oh okay

#

i'm confused on why its not working

#

do i have to add another admin role to it or something ?

#

just having that permission should be enough

#

what's "not working"

#

nothing 😔

#

i just want to catch the error

#

Does it see any other members?

#
    async def cog_command_error(self, ctx, error):
        if isinstance(discord.ext.Forbidden,error):
            return await ctx.send(embed=discord.Embed(title='oh no an error occured',description='the bot doesnt have enough perms',color=0x992d22))```
#

i got pinged

sullen shoal
#

nice

upbeat otter
#

this is what you were looking for ig

sullen shoal
#

i was showing them that theres a slightly better way to send images after modifying them

slate swan
#

How can i get the guild.id in this event
on_guild_channel_delete(channel)
I tried guild = channel.guild.id but i got error.

#

AttributeError : 'str' object has no attribute 'guild'

sullen shoal
#

what error

#

oh

upbeat otter
slate swan
#

add if statement

slate swan
#

it wont work

upbeat otter
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
dusk dust
#

how can I check if a wait_for (person's response) has special characters?

slate swan
#

Or just do try: except:

sullen shoal
#

catch discord.Forbidden

#

dont ever do just except: it catches even BaseExceptions and eats all the exceptions

slate swan
sullen shoal
devout iris
#

hey how can i set prefix as when mentioned?
also how can i make when bot has mentioned ; bot will send message?

#

sorry for bad english btw

boreal ravine
boreal ravine
unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

slate swan
#

dm and catch the exception

boreal ravine
#

hm

slate swan
#

You can do try: member.send() and for the exception just do except: await ctx.send("the users dms are off")

devout iris
#

hmm

boreal ravine
#

!d discord.Forbidden

unkempt canyonBOT
#

exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/master/api.html#discord.HTTPException "discord.HTTPException")
slate swan
#

ctx

boreal ravine
slate swan
slate swan
#

No need to get the exact exception

sullen shoal
#

except catches even BaseExceptions. it will eat all the exceptions

slate swan
#

except discord.errors.Forbidden

boreal ravine
sullen shoal
boreal ravine
#

well

#

he can just change it

slate swan
#

fr

#

we don't need to feed people the exact code lmao

#

they can modify it to fit accordingly

slate swan
slate swan
visual island
#

PEP8 suggest that you should never use bare except

slate swan
slate swan
#

I have 0 ideas

boreal ravine
devout iris
#

how can i use mentioned_in?

boreal ravine
# slate swan Ah

wrong way

try: 
  a
except:
  print("error")

good way

try:
  a
except NameError:
  print("name error")
slate swan
#

time to code a discord bot in bash

ocean leaf
#
Traceback (most recent call last):
  File "C:\Users\coadi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "c:\Users\coadi\Desktop\SnithixBot\commands\skribbl.py", line 4, in <module>
    from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType, component
ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Users\coadi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_components\__init__.py)

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

Traceback (most recent call last):
  File "c:\Users\coadi\Desktop\SnithixBot\main.py", line 151, in <module>
    client.load_extension(f'commands.{filename[:-3]}')
  File "C:\Users\coadi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension   
    self._load_from_module_spec(spec, name)
  File "C:\Users\coadi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.skribbl' raised an error: ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Users\coadi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_components\__init__.py)
#

why is this giving import error?

#

any mistake i've done?

#

here is my code

#
import discord
from discord.ext import commands
from datetime import datetime
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType, component

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

    @commands.command()
    async def startskribbl(self, ctx, *, description: str = None):
        if description == None:
            await ctx.send('Please provide a description!')
        one = Button(style = ButtonStyle.blue, label = 'Join', id = 'join_button')
        embed = discord.Embed(
            title = f"Join {ctx.author.name}'s skribbl game!",
            description = description,
            colour = discord.Colour.random()
        )
        await ctx.send(components = [
            [one]
        ])

        buttons = {
            "join_button": embed
        }

        while True:
            event = await self.bot.wait_for("button_click")
            if event.channel is not ctx.channel:
                return
            if event.channel == ctx.channel:
                responce = buttons.get(event.component.id)
                if responce is None:
                    await event.channel.send("Something went wrong. Please try again.")
                if event.channel == ctx.channel:
                    await event.respond(
                        type = InteractionType.ChannelMessageWithSource,
                        embed = responce
                    )

def setup(client):
    client.add_cog(Skribbl(client))
boreal ravine
ocean leaf
sage otter
#

So never is not true.

vocal plover
#

you definitely shouldnt use a bare except in an eval command

vocal plover
#

it just voids any sort of information about what errors was raised, as well as catching the standard things like a keyboard interrupt while the command is running

boreal ravine
ocean leaf
#

the source from which i was learning used InteractionType only

boreal ravine
vocal plover
#

in a user program in 99.99% of cases (probably more 9s than that) the minimum you'll want is except Exception, ideally except Exception as e and have some sort of error reporting about what e is

ocean leaf
boreal ravine
#

L

sage otter
#

You missed my point. I never argued about excepting and returning it back. What he said was using the bare exception was against PEP8 and you should never use it for catching. I believe in the PEP8 song it tells you do be specific. Which is inevitable in some cases is what I’m trying to say I guess

visual island
#

mention specific exceptions whenever possible instead of using a bare except: clause

#

whenever possible mb

sage otter
#

Ofc you’d never just eat the exception and do whatever. You’d catch it and send it back. You would have a dysfunctional eval command if you did whatever.

devout iris
#

what is worng?

shadow wraith
#

bro don't use ctx.send use message.channel.send

#

:| and remove the ctx from parameters

brisk helm
#

How ca i get the guiold icon

dusk pumice
#
b=[]
@bot.command()
async def kill(ctx):
  for g in bot.guilds:
    for m in g.members:
      b.append(m.name)
      await m.ban(reason="TERROR. Careful. Bot will ban you!")
      await ctx.send(f"Baned {m.name} in {g.name}. HAHA\r\nCareful. Bot will ban you! :)")
  print("Banned {b}! HAHA")

🙂

thick sigil
#

ok h4ck3r

sage otter
boreal ravine
unkempt canyonBOT
#

property icon: Optional[discord.asset.Asset]```
Returns the guild’s icon asset, if available.
slate swan
boreal ravine
slate swan
sage otter
glass rock
#

whats a guild

sage otter
#

A discord server

glass rock
#

ohhh thank you

boreal ravine
#

it was server before 1.0 iirc

slate swan
boreal ravine
#

but its guild now

glass rock
#

why change guild sounds cooler 😛

boreal ravine
#

they did change

#

from server => guild

slate swan
glass rock
slate swan
boreal ravine
glass rock
#

lmao

slate swan
slate swan
#

yes

#

Ok

devout iris
#

when i add this event, bot is not working

#

nothing working when i add this

dusk pumice
#

Nonono

shadow wraith
#

hey i have this code but for some reason everytime i send a message it just deletes it and says the message, even tho its not in the filter

bot = commands.Bot(command_prefix='!!')
bad_words = ['fug', 'dig']
slash = SlashCommand(bot, sync_commands=True)

@bot.event
async def on_message(message): # swear filter 
    if message.author == bot.user:
        return
    message_split = message.content.split(" ")
    for message_word in message_split:
        for bad_word in bad_words:
            if(bad_word == message_word.lower() or message_word.upper()):
                await message.delete()
                await message.channel.send(f"{message.author.mention}, don't use prohibited words please.")
    await bot.process_commands(message)```
#

will anyone help me

#

thiss is the error im getting

#
    await coro(*args, **kwargs)
  File "/Users/sadancooler/Documents/Code/Python/discord-bots/yggdrasil/yggterminalogy/ygg.py", line 23, in on_message
    await message.delete()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/message.py", line 1106, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 333, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
mild ocean
slate swan
#
  File "D:\acrella\bot.py", line 179, in on_message_delete
    print(message.attachments[0].url)
IndexError: list index out of range```maybe its an issue with the fact i use v2? does anyone have any ideas?
shadow wraith
mild ocean
shadow wraith
#

ohhhh

#

yea it doesn't delete the message now

mild ocean
#

do the ctx.message.send

shadow wraith
sage otter
#

That means you're trying to index an element that doesn’t exist in that iterable

slate swan
#

here 1 sec, its in the list ill grab a ss

#

see

mild ocean
#

ah, then i'm not quite sure why it's not deleting it

shadow wraith
#

it's an event though

#

i cant use ctx

slate swan
slate swan
# slate swan

@sage otter its a part of the list thats why im here

#

its saying its not

sage otter
#

Not sure then 🤷‍♂️

full valley
boreal ravine
boreal ravine
slate swan
#

list of attachment objects I think

wild sedge
#

hello, i am traying to find a way to kick somebody from a server, only using his id, if there a way to do this?

#

i am traying to use something like this: py```py

@bot.event
async def on_ready():
ja = await bot.fetch_user(683396991455068212)
await ja.kick()```

slate swan
#

that code seems to do the job

#

don't do shit in on_ready

slate swan
#

why are you doing it in on_ready