#discord-bots
1 messages · Page 602 of 1
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?
hey did they change they way you invite a bot to your server?
channelsend = bot.get_channel(channel_id)
im on the oauth screen but i dont see an invite link
yes, there are better ways than that actually what youre doing is completely useless
Code or smth
nvm
ok ty
Works?
self.bot.add_cog(minecraft.Minecraft)```
ein al ma kapara
if you want to load them automatically, you can have a look here https://github.com/m-y-x-i/simple-disnake-discord-bot/blob/main/bot.py#L26-L28
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()))```
lol
NameError: name 'self' is not defined
where are you doing it
In the class
https://github.com/m-y-x-i/simple-disnake-discord-bot/
you may look at my repo for help then
Okie
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
Go to Bot tab and change there
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
Still doesnt got it
cant help with that then
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
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
ohh ok
is there an event to detect whenever someone boost the server?
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)
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)
OH NVM I UNDERSTAND WHY
!e
print("HELLO ")
@formal pollen :white_check_mark: Your eval job has completed with return code 0.
HELLO
Tryitandsee
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?
whats the issue
do you need to fetch the message though?
When I run the program, r Count isn't printing (print statement is inside an if statement btw)
I did but by ID
you already have the message object though? from the for loop? or am i just being stupid.
!d discord.TextChannel.history
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...
Yeah I don’t know why you're fetching for
You get a sequence or something of message objects from that
I tried it without fetch but that isn't working too
did you import utils? is it supposed to be utils.get?
I imported utils
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.
yay!
Thank you
np
@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.
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
Look into checks and an error hadler
typehint time as None in your parameters.
async def mute(ctx, member: discord.Member, time=None, *, reason=None):
How to make an error handler - if the bot lacks rights?
rights?
why not just check it against ctx.channel.id?
It still persists saying I need to state the reason I'm doing .mute @hollow agate Test which my end goal is to make it do a permanent mute.
I'm not sure why it works without the permission check...
ok so you can do:
time: int=None
I believe?
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:
I believe that would work if my code allows only seconds for the mute time. It allows hours, minutes, days. There's a time converter in my code 😂
This is all super confusing
So a normal mute command would be .mute @hollow agate 3d Test
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.
Would you mind showing me it, it might give me a few ideas?
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 🤷♂️
What is [-1]?
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 😂
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?
what is something1 printing?
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
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
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.
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
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?
this is the error
it wont let me copy paste that for some reason
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
message.attachments returns a list of attachments.
!d discord.Message.attachments
A list of attachments given to a message.
!e
import random
print(random.choice([]))
@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
and?
your iterable is empty
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?
alr, not too familiar with postgres.
but when i used jisahku and fetched it, it returned a list
fk
tbh i would ask in #databases they may know more about how to help.
@visual island
did
and now its not even printing the error lmao
ok nvm
you mean default emojis
yes
i need a list of them in :format:
\😄
?
well if i did that
no i mean like default emotes in :format:
thats what happens
just press windows+. and you can choose the emojis from there , Why need the names of emojis
do \:smile:
Anyways, you can find them on a unicode emoji directory 😄 as well.
Exactly
||There is an emoji pack for python on pypi||
im trying to put a directory
how wold i do that
what is the directory?
ids/fetched.txt
and that is an existing directory?
yes
is it within your bots directory? so like the folder is in the same folder as your main.py file?
is the ids folder in same directory as your bot
./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.
it is
./fetched.txt```
like that?
that is current directory
ik
if its not in the current directory that is wrong
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.
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
sheeeeeeesh 😅
how can i return the url on its own
no
well i need to see where you are in relation to the file 😄
you will need to index the list and call its attribute
why do i get the feeling its kam
who u?
how would i do that? never done something like that
someone too important to be known
hi saage
whos saage
lmfao ok bud
k den
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.)
i figured it had to do with square brackets
make a bot.check() and check against a list of accepted users.
those would be indices. or an index yes
almost exclusive to lists and extracting data from a list or string.
@commands.has_permissions(manage_roles)
NameError: name 'manage_roles' is not defined```what-
neverminddd
manage_roles=True
Ok so I’ve switched over to vsc but it’s saying no module name discord when I try to import discord
dumbyyy
shush
if im right
if ctx.author == ctx.guild.owner```
is the same as
```py
if ctx.author is ctx.guild.owner```
right?
Indeed
why this gives an error
Does someone know how to solve it? When I was using that same bot in other server it worked very well.
@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("👍")
Yeah.
strange
do you have 2 factor authentication enabled on your discord account?
if not, your bot cant do moderation actions in servers with the 2fa requirement enabled
such as delete messages
Why does it say no module named discord when I try to import discord
I think not, I'll sett it.
pip install discord
I’ve tried that says no command “pip”
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
also has_role takes in either role names or ids, not keyword args for permissions
@commands.has_permissions also
Vsc terminal or the actual Linux terminal
so i didnt need administrator?
linux
just the ban_member?
pip3 for linux
pip3 install discord is how i did it
It’s doing something lmfao
Have you got python installed?
then it worked
Try doing python -m pip or pip3
i thi nk
I have python installed through vsc do I need to do it through Linux terminal aswell?
no
I’ve only ever coded on replit so never had to download or install anything
i think u need to install python and add it to path
oh sorry
i could be wrong
The python on visual studio code is a language pack, its for stuff like LSP stuff etc
It installed discord.py
You need to install python on your own computer
yes
yes that was i want to say
you should be good now
It wooooooooooorked!! I'm soooooooo happy. Thanks for this @vocal plover .
just restart vscode @
Happy to help :P
Ok
When I try to run my bot where do I look to see if it actually worked?
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.
Yeah no it’s not lol
problem with your code
take a ss of your vscode window
I figured it out 😂
ok
click the big red square
Ah ok
np i had a pain setting up vscode my first time 😹😹
Yeah it’s definitely something different
Now time to figure out why my unban command hates me
!d discord.Member.unban
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").
indentation = easy fix
Help me lmfao? I suck at cogs
If I can remember how to ss in chrome book 💀
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 == channelawait 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)
discord.Message objects have an attachment property, perhaps what you're looking for?
Ah I see, I will check it out thanks!@
put the least await inline with the first
ctx.channel is also = to just ctx so you could also do
ctx.send
A bunch more red pops up lemme run to see the actual error
but
well, ctx.channel is not just ctx, they are 2 different classes
but i see what you mean, just to set the record straight
yes i was just about to correct myself but i started eating 😹😹
Says await is outside function
put it inside the async function
It is I think?
click space on the for line
Ok red went away new red showed up
Yes it is indent error lemme take new pic
honestly you should revamp the whole command your indentation is pretty 💩
member_name aligned with banned_users
It’s going but not with cogs lol
Was it really that easy lmfao
yes
Ok let’s see what happens when I put it in vsc
Yeahhhh a bunch of red I hate this lol
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
Lucas unban
Yes lmfao
try using the role id instead
ok ill try
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)
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
Uhhh, u gotta convert to discord.Object(), the ID
wont typehinting it as discord.User already make it a discord.Object (snowflake)?
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
if its unable to convert it will already raise a UserNotFound exception
How do I make it so that my bot reads for a specific response only after it has sent a certain message
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**...
@client.command gets an error
it's client.command() though you should rename client to bot
@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 = ""
bot_owner = ""
bot_staff = ""
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
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'await' outside function
???
role_string is an empty string
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
thnx
How would I edit a message sent in another command?
fetch it
Not sure how to do that
you can use the Message.edit i think
yes but its in another command
idk
you can save the message object then just edit it there
Where would I save it
put the commands in a cog then save it as an attribute of the cog subclass
some of the comand will work better if u use cogs
myxi can u help me with my problem?
which problem
here
not sure never worked with voice stuff
so you dont want your users to use commands in other voice channels
either the Voice Channel is not in the bot's cache or the author is not in a voice channel
um my friend was admin and disconnect it from vc and the bot show that error
so its cant fixed or how mybe?
if i want to give the bot a role what would my code look like?
!d discord.Chunk
No documentation found for the requested symbol.
,-,
chunk?
!d discord.Member.add_roles
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.
yes, it requests the guild_data
thnx m8
you need to use the get function from discord.utils
i already got that imported i was just confused on what the code looked like
role_to_assign = get(ctx.guild.roles, name=rolename)
and add then just use .add_roles
!d discord.utils.get
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...
alright
btw is it showing NoneType for the bot or user?
for the bot
i tried to dc it and it show
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.
what would be the best way to do a server stats channel type thing
idk show screenshot
elaborate more.
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
Very "k"
Potassium
hm
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
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
!d discord.Member.ban
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").
wdym
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '>=' not supported between instances of 'int' and 'str'
how do i get the url of the member in on_member_join(self, member) it is in a cog?
what does this error actually mean
1 is a string while the other is int
both should be int or str
u can use int(x) >= int(y)
if(int(data.loc[str(id),"money"]) >= money):
this is the line showing
the money over there is a variable?
yep
and is the value of money a int?
yep
actually its a str i change it to int when using
as i use pandas module
then try printing type(int(data.loc[str(id),"money"])
and type(money)
to check if both are int
thx
np :)
how do i get the url of the member in on_member_join(self, member) it is in a cog?
Members don't have URLs?
nope
What are you saying then
member is just the username with #xxxx
yes
i need the url of their pfp
what URL though
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
so pfp = discord.member.avatar?
no
then
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
Me either
gimme a second to get the code lol
it works ty
Just convert the amount needed into the other thing
i could but it will take to long
otherone
why would it
You don't. As I said, use a database to store the guild ID and the respective channel ID for the statistics.
the embed already has enough latency
huh
embed's literally cant slow ur bot down unless its big 🤨
frankly i dont know what is about data.loc in int(data.loc[str(id),"money"].
see the problem is that its meant to run in one instance but in the hundreds
its running a 100 instances? or is it getting "100" latency
100 embeds with the same timer
oh ok its a module named pandas
Wtf show code
i heard about pandas but never used it
it is better if some one else helps u
hold i think i found a fix lol
this might be janky but it might work
pandas is a very rare using module
every second skid uses it nowadays
Is there a way to switch the bot from working per guild to let channel in a guild
idk what you are asking for
what
give more context
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
looks like some made up idea that you have to work on by your own
check the guild id then instead of the channel id?
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
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
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.
it will be called on each message your bot could see, you may use discord.Message.channel.id to identify different channels
hmm just not sure how I would adapt it to have a command that changes it between per channel/guild
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
alright ill see what I can do, thanks for your help
does anyone know how to code a discord bot
I've tried learning on youtube, I am learning but not the right way.
Do you know how to code in python?
yes
learn Python, OOP, python classes. then have a look at https://github.com/Rapptz/discord.py/tree/master/examples, and the docs at https://discordpy.readthedocs.io/
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
what do you mean by libraries
discord.py, fastapi and stuff
i know what I am doing but sometimes I could forget
in those times, docs will help you
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
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
why are you asking this in python programming language discord server
Why does he need to learn fastapi to use a library
read the conversation
ah
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
read the bold text, once your bot reaches 100 servers, you will have to verify your bot
so you dont need them
you have to turn them on to do specific task
but you dont need to verify untill it reaches 100 servers
thank you so much
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
check it on yt there are so many tutor and i arl made it myself with heroku
@commands.has_role(Giveaway_Host=True)```
why it give error :
```has_role() got an unexpected keyword argument "Giveaway_Host"```
I tryed some videos but not working
dm me
discord.Guild.create_text_channel returns the discord.TextChannel you created, in the code snippet, channel is the TextChannel object of the newly created channel
The channel ID.
so i do channel.id?
think and try
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
the doc is really helping me
item (Union[int, str])
it accepts int and str, so my guess is it either accepts the role id or the name of it
thank you
👍
what u mean? i didnt get it
ok sure
tq
!d discord.ext.commands.has_role is also there (just saying)
@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")
it didnt show the content i wanted to show so i gave the link
Ah, okay. Cool
Parameters
item (Union[int, str]) – The name or ID of the role to check.
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)
is there any docs for not loaded commands?
i maded giveaway commands but it doesnt show on help
not showing any error tho
wdym?
lemme grab screenshot about it
it doesnt give any error and i arl fixed has_role error
it can be help=""too
my other code use help="" and no problem
the reroll use help="" too
just use description="" and see what happens
Was the cog loaded
loaded
help works too
yea
!d discord.ext.commands.Command.help
The long help text for the command.
hm
anyerrors?
well it doesnt reply anything too when i used it
hm
and only this one still exits
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
okie ill try, maybe it can fixit too
from all commands
yeah
well i added it and it didnt show anything
Giveaways:
Reroll
Moderator:
is the cog long
and the giveaway command still not load
yes
all of my code or wht
just cog thats not loading
the cogs load but not the command
yes i have 2 command : Giveaway and reroll. reroll show but not giveaway
the command looks okay, i think some other part of the cog is causing it
lemme screenshot it
@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
I'm struggling on updating a past message sent by my bot
what u mean?
get the message and edit it
how can I get the id of a bot msg?
how
@commands.command(name="Giveaway", help="Made giveaway event")
@commands.has_role("Giveaways Host")
async def giveaway(self, ctx)
arl like that
right click the message and copy ID
i see dont indent it like that
it is supposed to be like this
mine are done, and if i had indentation issues i think heroku will make my bot offline rn
why're you using format and you have the same function name twice
wut?
you cannot declare two functions with the same name
.
the second command is working because, first one has been replaced with it
commands are no more but functions.
def foo(): print('one')
def foo(): print('two')
foo() # will print 'two'```
change one of their names @brave flint
yes tq btw for help
tq so much too
@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
yes one is i didnt look it too seriously and i think if it error it shown up with error message
name Giveaway in commands.command and giveaway while making the function
in the first one
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
oh okie
why is this saying: Bot has no attribute 'fetch_message'
the docs show fetch_message but it doesnt work
there are different ways to fetch a message, none of them includes Bot.fetch_message
thats the same thing I did
what you did is not correct
Then what do I do?
have a look at the link I sent, it depends on where you are trying to fetch it
and why
its all the same ,-,
All I need to fetch is the message of my bot using an ID
show me more of the code
thats all of it
more
try:
msg = await client.fetch_message(ID)
print(msg)
except Exception as e:
print(e)
the entire command
!d discord.ext.commands.Context.fetch_message
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.
Context is the first argument of every command
yes, so?
think
idk, am confused
discord.ext.commands.Context.fetch_message
Contextis the first argument of every command
I understood that, but will it fetch any message?
is it possible to update a bots code without restartng it
dont think so
!d discord.TextChannel.fetch_message
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.
it will fetch any Message but you cant edit them
thats the point
I mean if its in a cog then yeah, just unload the cog and reload it again
oh thanks 😦
cog?
or maybe it doesnt and only could fetch messages from the client
command group
whats that?
keep in mind, this will cost an API request, meaning if 50 people use it under one second, your bot will be rate limited
Nothing you should worry about
@boreal ravine ```
msg = discord.TextChannel.fetch_message(ID)
print(msg)
Why are you using the class
,-, wdym
your code
yes
wdym
discord.TextChannel.fetch_message()
^^^^^ ^^^^^^^^ ^^^^^^
class class method
``` yeah just get the instance of it don't use the class
it shouldnt work with the base class anyway
nvm
Use a database then? Why use local vars
wait locals vars restart too if you reload them 🤨
its for like a game where a player can make progress i dont want to save each step into a database
then what do you think a database is for
@sullen shoal thanks, I understood now, I'm quite dumb 🥲
👍
you can fetch the Message from discord.Member to edit them I think. (only if the Member is the client)
self botting
unless theyre doing stuff like editing a message with stats, yes
btw how much data does hosting a bot use per hour? A rough estimate would be appreciated
If its local it doesn't use data
internet bytes
discord.py makes requests to discords api ur bot doesn't use data
yees
the only way to know would be to calculate it yourself.
each request ranges from 2 to any amount in KB
so if it is idle it doesnt?
thats fair
Nope
as long as it isnt >200Mb/hr i should be good
ig
nope
wow
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
Nope
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
i see
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
Yups, a private one for only my bot (I have successfully completed it)
great
the first is a module rather than a class
well yeah
The commando temp mute on discord.py?
wut
how you do it?*
idk
damn mane , someone help me in #help-popcorn 😔
idk where i had the code
Would be so awesome Bro I've been trying to find a good solution since yesterday
its very old btw so the code i wrote is little dumb let me check tho
As long as it works, that's completely fine xd
ugh i deleted it some time ago
ohh mann :/
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
what the spoonfeed
just some copy pasta
thx
The spoofeed damn
I used numpy to make my corners rounded
i thought numpy is some math kinda module
looks like youre saving it as jpg
nope
show code
png
entire command
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')```
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)
doesnt that code block the script
i mean mine does too ik
That's why it's ran in the executor
oh
Whats an "executor"
but the thing is it could be better
It breaks for noob pfps tho (default dc avatar)
hate you <3
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
d! events
#bot-commands

So should i use it or na?
it doesnt do what you want
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)```
role hierachy?
are you trying to kick someone that has the a role superior to the bot's top role?
nope
I see
then your bot doesn't have perms to ban
yep
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
that's the default
!d discord.Member.ban
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").
simply have the kwarg delete_message_days to 0
await user.ban(reason=reason,delete_messages_days=0)
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
nice
this is what you were looking for ig
i was showing them that theres a slightly better way to send images after modifying them
ah okay
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'
try using the the get method on channel
add if statement
Get method for dictionary right?
it wont work
!d discord.utils.get
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...
Ohh alr alr
how can I check if a wait_for (person's response) has special characters?
Or just do try: except:
catch discord.Forbidden
dont ever do just except: it catches even BaseExceptions and eats all the exceptions
make a list called special_characters and use for and in to check if they're in the response
str.alpha is a string method that checks if all the characters of a string are alphabets or not. you can wait for a message and get its content by discord.Message.content
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
!d discord.ext.commands.Bot.when_mentioned
!d discord.ext.commands.Bot.when_mentioned_in
No documentation found for the requested symbol.
dm and catch the exception
hm
You can do try: member.send() and for the exception just do except: await ctx.send("the users dms are off")
hmm
!d discord.Forbidden
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")
ctx
do not.
y not
Why not exactly?
except catches even BaseExceptions. it will eat all the exceptions
except discord.errors.Forbidden
try:
...
except discord.Forbidden:
...
now look what they did there
fr
we don't need to feed people the exact code lmao
they can modify it to fit accordingly
Ok my bad ig
^
PEP8 suggest that you should never use bare except
Why is that so?
@slate swan
What does he mean by eat all the exceptions?
I have 0 ideas
raising all the errors that can be raised
Ah
how can i use mentioned_in?
wrong way
try:
a
except:
print("error")
good way
try:
a
except NameError:
print("name error")
Makes sense thx
time to code a discord bot in bash
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))
InteractionType doesnt exist
then what is it?
That’s objectively false. It’s acceptable in certain cases. Especially in an eval command where you never know what error will be raised.
So never is not true.
except Exception:
you definitely shouldnt use a bare except in an eval command
Elaborate.
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
why should I know? I don't use the library.
the source from which i was learning used InteractionType only
old_tutorials_are_bad.exe
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
bruh
L
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
mention specific exceptions whenever possible instead of using a bare except: clause
whenever possible mb
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.
bro don't use ctx.send use message.channel.send
:| and remove the ctx from parameters
How ca i get the guiold icon
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")
🙂
ok h4ck3r
api aboooz pls ban!!
!d discord.Guild.icon
!d discord.Guild.icon get the guild instance > use the icon attribute on it
property icon: Optional[discord.asset.Asset]```
Returns the guild’s icon asset, if available.
Whats that?
doing shit that rate limits ur bot
Oh bruh
.url to be specific since it’s a asset.
whats a guild
A discord server
ohhh thank you
it was server before 1.0 iirc
The object of a discord server
but its guild now
why change guild sounds cooler 😛
I just realized that bans all members in a guild lmao
oh ye didnt see edit thank you
miniscule amount of trolling
yes it iterates through the guild's members and yeets them
lmao
Yuh
Iterate means going through? I dont have a direct definition of iterate
yes
Ok
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```
await message.delete()
await message.channel.send(f"{message.author.mention}, don't use prohibited words please.")
looking at these 2 lines
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?
i dont think there's any problem
you first delete the object, then you are trying to access its attributes/methods/data.. you should swap the two lines and try again 🙂
This is basic python
do the ctx.message.send
this is an even-
That means you're trying to index an element that doesn’t exist in that iterable
ah, then i'm not quite sure why it's not deleting it
ctx.message.delete
Not sure then 🤷♂️
That ain’t no list 
message didnt have an attachment
I mean it isn't, but message.attachments returns a list
list of attachment objects I think
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()```
Won't work
why are you doing it in on_ready