#discord-bots
1 messages · Page 573 of 1
which is that cmd when i delete the msg where i used that cmd the response also gets deleted
can you edit images with this?
If anyone knows js i'm python
async def on_member_join(self, member):
channel = self.bot.get_channel(903695632877895693)
await channel.send("Welcome!", member)```
why is it that when I try to send the message
it comes up with this error : send() takes from 1 to 2 positional arguments but 3 were given
This channel is for Python, not javascript
Because your passing member as another parameter
exactly! but I've been on all platforms to find out about this and I didn't find it and you were the only one who answered me so far
Thanks
It should be something like:
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(903695632877895693)
await channel.send(f"Welcome {member.mention}!")
For example
Thanks
I missed the f for the f-string
Hey @shut axle!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
It should be working now, tho
Thanks !
https://paste.pythondiscord.com/awalagopon.py
It is not sending anything. no errors/
anyone know anything about this
There's no discord.client.
can someone add my bot into my server, i am on my school computer, at school, and discord.com is blocked. i have an unblocker for discord but hcaptcha doesnt show on this. so I cant verify.
shut it
@dapper cobalt ```py
from discord.client import client
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
from discord import Client
uppercase
HOkay
can you edit images that are attached to a message with message.edit()
No.
which is that cmd when i delete the msg where i used that cmd the response also gets deleted
ive seen some people doing it on a bot tho 
@shut axle do from discord.Client import run and then do py if name != "__main": import os os.system(await run)
thats how you maake a bot
@manic wing it shows me that client is not defined.
I didn't use it.
help??
🤦♂️
await run? 
!d discord.Client.run
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").
Roughly Equivalent to...
What have I just witnessed?
Cringe
print(os)
You imported os twice?
out of all the troll in that, you only noticed the await run?
!e
import os
print(os)
# I just need to know what the heck this actually prints.
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
<module 'os' from '/usr/local/lib/python3.10/os.py'>
My brain is not working
Good to know
you're not being serious right?
I couldn't have been more serious.
This channel is not for trolling 
which is that cmd when i delete the msg where i used that cmd the response also gets deleted
HELP?
trolling != misleading beginners
Bro just
await
saw what i just did their 
code:
async def whois(ctx,user:discord.Member=None):
if ctx.channel.id != 835236006713098304:
async with ctx.typing():
await asyncio.sleep(0.4)
emb2=discord.Embed(color=0x2f3136)
emb2.add_field(name="Nickname:", value=f"`{user}`")
emb2.add_field(name="ID:", value=f"`{user.id}`")
await ctx.send(embed=emb2)
return
Why doesn't my bot write anything?
Cheesy joke
Maybe
whats the error
i assume there are no errors here?
and this is inside of a command?
yes
What is user?
Did u call the command?
Ah, nvm.
no error
what did u type in the cmd?
user:discord.Member=None
nothing
He asked how did u use the command
clear
like: ?whois @user ?
yep
yes,but I threw off part of the code
which part?
from the main code "whois"...
there are many ways to evaluate what might be incorrect;
a) put a print at the start, to see if it triggers; dot prints around, to see where it ends
b) revisit an error handler, maybe there is an error that we are missing.
c) print(ctx.channel.id)
d) check perms for the bot, maybe you catch discord.HTTPException's
yes, but it works if the user does not exist
async def whois(ctx,user:discord.Member=None):
if user is None:
user = ctx.author
if ctx.channel.id != 835236006713098304:
async with ctx.typing():
await asyncio.sleep(0.4)
emb2=discord.Embed(color=0x2f3136)
emb2.add_field(name="Nickname:", value=f"`{user}`")
emb2.add_field(name="ID:", value=f"`{user.id}`")
await ctx.send(embed=emb2)
return
do this
edited it ^^^
You can do something easier than an if statement. user = user or ctx.author.
Yes
If user is None it will take ctx.author; hence None is pretty much equal to False.
ik but that guy dont know what that will do so i did like that....
Exactly, I forgot to add
if user is None:
user = ctx.author
Thank you
Are u using bot or client
without cogs
Does it show that the bot is typing, tho?
ahh anyone help me now.....?
yes?
if ik I can help lol 😂
this..
write here, everyone will help you.
can someone help with an error with discord bot with an equal sign and ModDeleted not defined?
Clear command?
i already did lol
no broo
Then?
async def whois(ctx, member:discord.Member=None):
member = member or ctx.author
if ctx.channel.id == 835236006713098304:
return await ctx.send("You cannot use that here!")
embed = discord.Embed(color=0x2f3136)
embed.add_field(name="Nickname", value=user.nick)
embed.add_field(name="ID", value=user.id)
await ctx.send(embed=embed)
Try that.
I have already been helped, thank you
Oh that was your issue, not his.
the cmd of @unkempt canyon like when i use that cmd and i delete the invoked message the bots reply also get deleted
msg = await ctx.reply("You cannot use that here!")
await asyncio.sleep(5)
await msg.delete()
await ctx.message.delete()
You can also pass delete_after attribute to ctx.reply.
Yup
can someone help with an error with discord bot with an equal sign and ModDeleted not defined?
no
delete_after=second
Then 😂?
let me show
k
@stiff nexus :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'test' is not defined
see if i delete this message the bot should delete its reply message
like that
reply message = ^^^
explain
what is ModDeleted
You can do that using:
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_delete
If mod deletes message if not then false
ik the event lol but how to know they invoked the cmd
i get it but can u send the whole code?
sure
ok
I haven't used it in my bot.. I think u call the event, the do smth like if author msg is deleted then delete bot msg
@client.event
async def on_message_delete(message):
channel = client.get_channel(904216460010872832)
if not message.author.bot:
async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
if entry.created_at.now() == datetime.datetime.now():
ModDeleted = True
embed = discord.Embed(title="Message Deleted By Mod")
embed.add_field(name="Member: ", value = message.author.mention, inline=True)
embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
embed.add_field(name = "Message: ", value = message.content, inline=False)
embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)
await channel.send(embed=embed)
if ModDeleted == False:
embed = discord.Embed(title="Message Deleted")
embed.add_field(name="Member: ", value=message.author.mention, inline=False)
embed.add_field(name="Message: ", value=message.content, inline=True)
embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)
await channel.send(embed=embed)
u need to define who is ModDeleted here
is this how you do it i forgot how
member = discord.Member
where?
the user that sent message if they have manage message perms or not
wait nvm i know now
member:discord.Member
yeah
Where did u define it?
ok u know it now tell me how will the bot know this???
1st you need to check whether the user has mod perms or not
ummm hmm i don't see it
lol
how
how do i do that with a true of flase question for the bot
U want the bot to say "you can't use that cmd" if the user does not have perms?
u cant bruh
It limits the cmd
ya
Yeah
but he is doing a event lol
Just make a separate error handler
that u can
How can i set ping command as embed?
!docs discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
lol it is not that it is a log part
@stiff nexus i did embed but i have a few errors
let see
Code?
code
A sec
I don't understand what ur trying to do
I do mine like this or like thispy embed=discord.Embed(title='How long it took', description=f'The command took {time.time()-t:02.02f} seconds to run!', color=0x1f8b4c)
embed = discord.Embed(title="Message Deleted")
embed.add_field(name="Member: ", value=message.author.mention, inline=False)
embed.add_field(name="Message: ", value=message.content, inline=True)
embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)```
here go to #help-orange
@client.event
async def on_message_delete(message):
channel = client.get_channel(904216460010872832)
if not message.author.bot:
async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
entry.created_at.now() == datetime.datetime.now()
if ModDeleted = True Then:
embed = discord.Embed(title="Message Deleted By Mod")
embed.add_field(name="Member: ", value = message.author.mention, inline=True)
embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
embed.add_field(name = "Message: ", value = message.content, inline=False)
embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)
await channel.send(embed=embed)
else:
embed = discord.Embed(title="Message Deleted")
embed.add_field(name="Member: ", value=message.author.mention, inline=False)
embed.add_field(name="Message: ", value=message.content, inline=True)
embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)
await channel.send(embed=embed)```
it is a log event
What can i do?
title = F"Ping: {bot.latency}MS"
.
@bot.command()
async def ping(ctx):
em = discord.Embed(description=f"{round(bot.latency*1000)}ms")
await ctx.send(embed=em)
ty i'm trying
Ty it is working
guys, why isnt this working?
@client.command()
async def rename(ctx, name):
try:
await client.user.edit(name=name)
except Exception as e:
print(e)
Np 👍
what does it print
Idk sry 😔
nothing
I think you need password or some shit
me too
it worked fine before
ok
thankee
Try it, dk if it works... It requires password or smth like caeden said
username=
but it should error 
How can i find color codes?
Hex color codes?
No, hex codes aren't working in embed i guess.
They will work
There is color code in embed message
mine is not issue it works fine
Stack Overflow
I found it a bit difficult and annoying to change colors in discord.py (embed color for instance). I made a class for the different color codes to use in discord.py which can be imported into the m...
didn't add anymore imports for it
@devout iris
U can do this
em = discord.Embed(color=discord.Color.blue()) # for blue color
Thx
Np 👍
How do you do timestamps with the bot?
Has discord.py been discontinued?
same thing on how you do timestamps
you mean like <t:123123123:R> ?
how can i make it error when a normal user uses this command??
it already sends an error, you just gotta handle it
@client.event
async def on_ready():
print("==================")
print("Logged in as")
print('{}'.format(client.user.name))
print("{}".format(client.user.id))
print("==================")
print('Servers connected to:')
for guild in client.guilds:
print(guild.name)
print(guild.id)
print(guild.members)
print("==================")
How would I go about making this print how many members are in a server as a number?
Guild.members lists each member individually
It's a list, get it's length with len()
Basic Python
How would I implement that?
Literally wrote it
guild.members returns a list, get it's length with len()
If you don't know how to do that, consider learning Python
And consider using f-strings
Discord.py is not supposed to be for beginners as stated multiple times in the documentation
!resources
Resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
https://pythondiscord.com/resources
Will help you to start learning Python
!warn 897958982159859742 Let's not use homophobic slurs in this server please.
:incoming_envelope: :ok_hand: applied warning to @slate swan.
@slate swan Please try not to engage in gate-keeping behaviour. This pinned message explains it better than I can: #discord-bots message
thank you so much I didn't know how to do that I had the member welcome not adding roles so I just modified it to fit my bot parameters and it worked I didn't just copy and paste it i worte it on how i needed it and i only needed half
Yw
why isn't this working? it worked at 12:00 pst time now it doesn't messed around with it because it did half ```py
ModDeleted=commands.has_permissions(manage_messages=True)
Not_ModDeleted=commands.has_permissions(manage_messages=False)
@client.event
async def on_message_delete(message):
channel = client.get_channel(904216460010872832)
if not message.author.bot:
async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
entry.created_at.now() == datetime.datetime.now()
if ModDeleted:
embed = discord.Embed(title="Message Deleted By Mod")
embed.add_field(name="Member: ", value = message.author.mention, inline=True)
embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
embed.add_field(name = "Message: ", value = message.content, inline=False)
embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)
await channel.send(embed=embed)
if Not_ModDeleted:
embed = discord.Embed(title="Message Deleted")
embed.add_field(name="Member: ", value=message.author.mention, inline=False)
embed.add_field(name="Message: ", value=message.content, inline=True)
embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)
await channel.send(embed=embed)```
aw man ur code isnt working 😦 lemme go through ur ide so i know the error
are you being sarcastic? with the first part
🤷♂️
find the error?
ok the error is it only works half and now not at all nothing in terminal
The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage.
You should do if entry.user.guild_permissions.manage_messages.
Not if ModDeleted because you're simply not specifying which user you are trying to know if they have the permissions or not.
How would I go about making a command that can be run in one server that does something in another? For example if I typed !say (channel or guild ID) (message) it would say it in a different server?
use get_channel to get the channel by id and then use .send to send it to that channel
this is an interesting question
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
and this ^
Would this work for guild dms?
huh
wdym
guild has dms now?
thanks let me see if that fixed it
Yes. You can even send friend requests to guild.
wait whatt
is it in docs
and if so please link docs
ik ur kidding
No, but it's in your dreams.
i will rage quit
Like I have an old server that I can’t make an announcement in anymore due to losing perms cos new account but I have an old bot in there and I want to be able to make it dm everyone in that server to send our new server
haha so funny
I know.
Would there be a somewhat easy way to make it so I can just use a command to dm users of that server specifically and not any others the bots in
just write the code normally
because the bot token is on that server
so it will work
I can’t get an invite to the server either I lost it completely so I can’t run the command from there
@slate swan but ur inactive on this acc
How would I do it externally
oh
I’m inactive in general aha tryna be more active
maybe webhook
i think you can create webhook using bot then send to that webhook
better yet just have the bot create an invite and print it in termal if possible
yh
but he has to use cmd as his chat to run commands
not on an event
https://stackoverflow.com/questions/69744533/how-to-create-webhook-with-python-discord-bot check this out
we are thiinking
wdym
I’ll figure it out eventually will just be way to much code for something that will probably be real simple
bruh my dumb internet
if you have guild members when you run the bot maybe you can dm one of them in your account
im sorry what do you mean by this
yh
are you still on the server or are you completely off it
Completely off it, I have the guild ID, want to dm the members in that server a message explaining what happened with a command like !say (guild id) (message) in a different server.
Hopefully that’s a bit of a better explanation
I have the actual command just need a way to use guild id in it
I’ll send in a second
ok i get
and got one thing happen in one it logs in another
and that was on event
or command'
@client.command()
async def alert(ctx, *, message):
for user in list(ctx.guild.members):
try:
await asyncio.sleep(0.5)
await user.send(message)
await ctx.send(f'Sent "{message}" To {user}')
except:
pass```
That works but only where the command is run
so if you have server id then you can run the command from another server
Yes
or channel id
isnt that what you wanted?
so you need a way to run this on your server
No, I need to run it in the server but I can’t do that.
cuz you used ctx?
i have an idea
I need to run it externally
i got it
let me make it
kk
do you have a channel id?
my idea is webhooks
Not a channel ID no
lemme google
I would be able to
But I don’t think it’s to necessary
As I should only need the guild ID right?
it if you want to use it externally
why do you want channel id when he wants to send it to the members?
https://stackoverflow.com/questions/63321098/is-it-possible-to-get-channel-id-by-name-in-discord-py read thus u quess
hmm
That’s nothing like what I need..
I need to dm them not send something in a channel
do you have a server id
kk lemme keep thinking
i get
Yes
hmmmmm
may I have it
how does that help ??
because i am writing it out to send externally
Ok
ok i get
im still thnking about webhooks
try not to spoonfeed
do you have any webhook on that server
ok give me a minute
No
ok
why do you want to use a webhook?
Webhooks are not what I need anyway
you can send info into the server using webhook
thats why i make one for every server i have
@slate swan use get_guild and then iterate over it and then send the message to all the users in that guild
just incase
How would I implement that into my code?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
try this
async def alert(ctx, *, message):
for user in list(773795551845154816):
try:
await asyncio.sleep(0.5)
await user.send(message)
await ctx.send(f'Sent "{message}" To {user}')
except:
pass```
huh?
this is why you use syntax.
I found that out
lmao im loosing brain cells
This server is cooked
why
Normally helpful lmao
bro this is not easy problem
Somehow managed to find people more incompetent
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Thanks
use that to get a guild obj from the id and then iterate over the members from it and use .send to send the message
!d discord.User.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
if guild.partnered == True:
partner = ""
else:
partner = ""
if guild.verified == True:
verified = ""
else:
verified = ""``` want to check if the server is partnered or verified and put the badge of the server, but guild.partnered isn't correct and guild.verified too
how it would be?
thats guild.features
not guild.partnered
guild.features returns a list, check if partnered and verified is in that list
it doesn't i made an error in it
better your way i think
how can i delete all roles with one command? i am trying in my own server but i don't know how
k
nah im done giving help im inexperienced at this and i always receive hate comments
i thought this server wuld motivate me to code but i feel very demotivated to anything
how i can i send a regular message and embed in the same message? e.g i want it to @ the user before the embed
use a for loop on the guild's roles (ctx.guild.roles) and then do await role.delete()
as you would normally, .send("@mention_here", embed=embed)
whats the thing that makes your text to python
thanks i needed the ctx.guild.roles part
yw
!codeblock
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
thx
np
import discord
import json
import os
from discord.ext import commands, tasks
class xp(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
with open("users.json", "r") as f:
users = json.load(f)
await update_data(users, member)
with open("users.json", "w") as f:
json.dump(users, f)
@commands.Cog.listener()
async def on_message(self, message):
with open("users.json", "r") as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open("users.json", "w") as f:
json.dump(users, f)
await bot.process_commands(message)
async def update_data(self, users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]["experience"] = 0
users[user.id]["level"] = 1
async def add_experience(self, users, user, exp):
users[user.id]["experience"] += exp
async def level_up(self, users, user, channel):
experience = users[user.id]["experience"]
lvl_start = users[user.id]["level"]
lvl_end = int(experience ** (1/4))
if lvl_start < lvl_end:
await bot.send_message(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
users[user.id]["level"] = lvl_end
def setup(client):
client.add_cog(xp(client))
On line 28 theres an error, name 'update_data' is not defined
bot.send_message is no longer a thing
I don't know hy
Use channel.send
does this work whn hosted online
why are you using json?
Idk I just found it on yt, and i find it easy
maybe to store user names idk
what else?
that's basic python OOP, to access methods within your class you add the self before it (await self.update_data(...)), please learn more about how classes work, there's a tutorial in pins
use an actual database
isnt it laggier (what a friend told me)
WHAT?
It's gonna be a bot for only one server so no big deal
it's not, database is always better than json for storing data
idk but ur friend is lying to u
^^
he told me to use json since fatabase laggy
oh
use python or HEROKU
it's the other way around actually 😂
wtf is fatabase
lmao
:kek:
😂
??
hey who here using replit to host discord bots
python or heroku?
imagine using it
me using it XDD
use heroku instead, better than replit
lol
heroku is more tedeous
because i dont have git
still a lot better from my experience with both
and its so confusing
¯_(ツ)_/¯
yes if they are using json why not python instead this a python server and host it on HEROKU i do and it doesn't lag or i can't notice how do i setup a command to get a time count?
ok i will check it out
ok gn
gn
what-
gn? it is 2:31 pm for me what time for you
json != javascript just so you know
?
11 32pm here 😂
o
@kindred epoch
@bot.command()
async def features(ctx):
guild = ctx.guild
await ctx.send(f"{guild.features}")```how i can make that if that contents partnered or verified it puts a emoji? @kindred epoch
how do you setup a proper ping command? i just have pong command
@echo wasp json is just a file system, you can use it to store data in the form of a "dict", python is a coding language, they're 2 completely different things, and heroku is a host provider
import discord
import json
import os
from discord.ext import commands, tasks
class xp(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
with open("users.json", "r") as f:
users = json.load(f)
await self.update_data(users, member)
with open("users.json", "w") as f:
json.dump(users, f)
@commands.Cog.listener()
async def on_message(self, message):
with open("users.json", "r") as f:
users = json.load(f)
await self.update_data(users, message.author)
await self.add_experience(users, message.author, 5)
await self.level_up(users, message.author, message.channel)
with open("users.json", "w") as f:
json.dump(users, f)
async def update_data(self, users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]["experience"] = 0
users[user.id]["level"] = 1
async def add_experience(self, users, user, exp):
users[user.id]["experience"] += exp
async def level_up(self, users, user, channel):
experience = users[user.id]["experience"]
lvl_start = users[user.id]["level"]
lvl_end = int(experience ** (1/4))
if lvl_start < lvl_end:
await channel.send(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
users[user.id]["level"] = lvl_end
def setup(client):
client.add_cog(xp(client))
``` **I've added the selfs, but now the xp doesn't update + it doesn't give an error so Idk wat im ment to do**
@slate swan
check if they verified and partenerd is in the list by using if statements, and then do what u did before
I've changed it look
@slate swan may i ask you another thing
?
oh i see
how do you setup a proper ping command? i just have pong command like to tell how long the react time is
!d discord.ext.commands.Bot.latency
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
do you know how .send works?
how do i send a message with buttons
ok so basically, if the bot tries to delete an integration role (like his own role) it gives an error and the loop stops, how can i make it not happen? i probably need a try: and except: thing right?
Yeah?
are you sure?
99%
by making a view and when you send the message you pass in the view using the view kwarg (you need python 2.0, master version)
so how do i set it up? don't know the property family very well
i can clearly see you dont
how do i make a view 😅
Get bot.latency then multiply by 1000 since you probably want the ping in ms
where?
btw this code is stolen from stackover flow i didnt make it
await channel.send(channel, ...)
Why do you have channel as parameter?
await channel.send(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
so like so? py @bot.command(name='Ping') async def Ping(ctx): await ctx.channel.send(f"pong took {bot.latency*1000} ms!")
Yes, but use f-strings correctly
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
import discord
class MyView(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Click Me")
async def my_button(self, button: discord.Button, interaction: discord.Interaction):
await inter.response.edit_message("Thanks for clicking me!", ephemeral=True)
# Somewhere in a command:
await ctx.send('Hello', view=MyView())
Thanks!
statements?
there's also examples if you visit the repo
if statements, do you know what that is?
so? py @bot.command(name='Ping') async def Ping(ctx): await ctx.channel.send(f"pong took {bot.latency*1000} ms!")
oh nice will take a look at these
Try it and see, and you can just do ctx.send instead of ctx.channel.send
right i'll fix that but it told me this
Yup
Now you can just round it to an integer with int()
Then it will be an integer instead of a float
no xd
!resources
Resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
https://pythondiscord.com/resources
tnx
You should take a look at learning Python before doing bots and projects
so? py @bot.command(name='Ping') async def Ping(ctx): await ctx.channel.send(f"pong took {int(bot.latency*1000)} ms!")
ok sorry never mess with this stuff
It basically converts what's inside the () to an integer
Same for str(), float(), etc.
@echo wasp do you know python?
yes but never mess with this stuff directly
@client.command()
async def send(ctx, guildid, *, message):
for guild in client.guilds:
guild = client.get_guild(guildid)
members = (guild.members)
for members in guild.members:
try:
await asyncio.sleep(0.5)
await members.send(message)
await ctx.send(f'Sent "{message}" To {members}')
except:
pass```
So I have figured out server by server command but now it keeps saying object has no attribute “members” on the ` members = (guild.members)` line
how can you check if a role is deletable or not?
!code please
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Fixed sorry
Why do you do a for loop to later overwrite all the time the guild variable?
guild will always be the same, you can delete your for loop
why did you define guild.members "members" and used "members" in the for loop
https://www.w3schools.com/python/python_conditions.asp can u use this to learn python @kindred epoch ?
Should I use member or user instead?
ive heard w3 is bad
mhm
why are you asking me? if you know what i mean and know enough python you should fix it by yourself
why do you need 2 *
ok?
- is used to get all the text after the arg its put after
i said all the text not 1 thing
c++ the best
ok and?
it is
what
send the error
ah ik
use get_channel
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
bc the bot not in that guild?
guild has no attribute channel, thats why its not working
someone can help me to add roles on a member in my server with a command mention in the tchat
thats why use discord.Guild.get_channel to get a channel obj from a certain guild and then use .send on it
:incoming_envelope: :ok_hand: applied mute to @void mortar until <t:1635804489:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 125 newlines in 10s).
what do you have?
uh
!unmute 386179923364151307
:incoming_envelope: :ok_hand: pardoned infraction mute for @void mortar.
!paste please
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.
"Damné" is the name of my role in my serv
add_roles takes a role obj not a str, use get_role to get a role object using the id
@bot.command()
@commands.has_permissions(administrator=True)
async def addrole(ctx, role : discord.Role, member : discord.Member):
pseudo = member.mention
await member.add_roles("Damné")
await ctx.send(f"le role a correctement été donné à {pseudo}")
put it before the .send, then use the id the members used in the brackets so something like this:
guild = bot.get_guild(guildid)
channel = guild.get_channel(channelid)
await channel.send("hi")
just the part of my script addrole ?
"Damné" is the name of my role i resay
what are you doing lmfao
get_guild(id, /)```
Returns a guild with the given ID.
click on the title and read what it does
<3
bro ur supposed to change it to guild.id and channel.id
holy shit im not going to spoonfeed u
no it was the result of print(*dir(discord.Guild), sep='\n') xd
and i asked u to read what get_guild does
@onyx skiff please learn more python before using a not beginner friendly library.
you having fun here? xD
@kindred epoch i'm a got on python you d'ont know that and i have the lmfao attribute
@forest lion can you send the error
@kindred epoch you don't know that I live in PAris and I am in the family of Emmanuel Macron
and I eat bread and croissant every mornings
nice to know
actually, can you try changing guild and channel attributes to int, and then try it
you can’t typehint to discord.Guild afaik
@kindred epoch I visit the eiffel tower with the lmfao attribute
good job
@kindred epoch are you jealous a little bit ?
why would i
because I've the lmfao attribute and not u
ok
@kindred epoch say a french word to e please I like the strange people
!ot
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
!va te faire enculer @kindred epoch
change discord.Guild and discord.TextChannel to int
do you think i dont understand that
A: https://paste.pythondiscord.com/ziqibavino.py
B: photo bellow, not 2 help commands
C: file runs correctly, only 1 help command and i only have 1 command
@kindred epoch help please
use the attribute help_command=None in ur commands.Bot
expain how to apply that to my code
it was working fine until i added the Case sensitive
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
its right there
I never set that up so now i am confused?
I used my own command is it because i am going insensivtive?
then whats this?
client = commands.Bot(command_prefix='&', intents=intents, owner_id=786788350160797706, case_insensitive=True)
never added the help command
oh how
.
so just add the name of the command that has it?
add help_command=None
still same prob with that added
show where you addded that
show the error
Shown
did you save and restart the bot?
ok then idk
so do what then email discord lol
yes
he just helped me
just ping him
can you show code
channel is none
@kindred epoch it run just fine when i removed ```py
, case_insensitive=True
so how do i make it not case sensitive
yep
put it after that
i did
print(channel.id) for me
that is where i had it
can you expain how to rewrite it so it works properly?
i have no idea why it does not work
can you rewrite the client=command part they way you know it
@bot.command()#6600 ##Usage: grid!send <serverid> <channelid> This is a test message
async def send(ctx,guild: int,channel: int,*,message):
guild = bot.get_guild(guild.id)
channel = guild.get_channel(channel.id)
await channel.send(f"{message}")
``` @forest lion try this
wait remove .id
@bot.command()
async def send(ctx, channel: int, *,message):
channel = bot.get_channel(channel)
if channel:
await channel.send(f"{message}")
client=commands.Bot(command_prefix='%', intents=intents, Help_command=None, case_insensitive=True)```
please dont use ableist language
why remove the help command? it looks nice
sorry
because i have my own
and my file won't work
oh, alright
so my bot won't launch
it looks nice tho- at least i thought
never saw it
ah, ok
so can you help with my error
which is?
this
it still is broken i stumped him
nope
try bot.remove_command('help')
well, to be honest the best way of doing a help command is to sub-class HelpCommand.
Here is a guide:
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
of course its up to you
not my help menu
my help menu
yes so when i do case insensitive i get a not launching even though i disabled that
top one
and
it works when i do this
just not when i do this
make case insensitive to True and do this before defining your help command
actually
client.remove_command
idk if this may be causing issues. Probably
bot=client
well it just went with what you told me
it worked great thanks
np!
yay thanks so much
Help this only works half can someone expain why? It just does it when the bots delete the message not if a user deletes them
@client.event
async def on_message_delete(message):
channel = client.get_channel(904216460010872832)
if not message.author.bot:
async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
entry.created_at.now() == datetime.datetime.now()
if entry.user.guild_permissions.manage_messages:
embed = discord.Embed(title="Message Deleted By Mod")
embed.add_field(name="Member: ", value = message.author.mention, inline=True)
embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
embed.add_field(name = "Message: ", value = message.content, inline=False)
embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)
await channel.send(embed=embed)
else:
embed = discord.Embed(title="Message Deleted")
embed.add_field(name="Member: ", value=message.author.mention, inline=False)
embed.add_field(name="Message: ", value=message.content, inline=True)
embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)
await channel.send(embed=embed)```
bc of if not message.author.bot ig
how do I import pycord
Hello guys, been a while since I've done some discord bot coding. And would like to ask whats a good replacement for discord.py, since it was discontinued a while back.
you can import a package by writing import pycord at the top. and just do a pip install pycord.
and there's no other changes from dpy yet I assume?
Same, I have a bot that has quite a bit of code and i would perfer not to have to rewrite but still keep up with discord updates
sorry it is the other way around it does it when the bot goes but not when i delete a message
Please ping with a response
this caught my eye, https://github.com/nextcord/nextcord. anyone tried this yet?
no, but i use this https://github.com/Pycord-Development/pycord
GitHub
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
both look very even to me
pycord has about 2 times as many stars on github and a more offical looking support discord but it looks like nextcord is trying to be good as well.
Another thing in the d.py discord i looked at servers that the online nitro boosters were in, about half of the 15 were in pycord hlaf were not in either and 1 person was in nextcord (they were also in pycord tho.)
I think I am going to go with pycord for now
i watched this video on sqlite3 https://youtu.be/Y9DzfPJsP2s but i dont really understand it- my bot is in a couple of test servers and when someone joins one of the test servers, it sends a message to my server saying this message even though they never joined mine, so im just trying to make that stop
import discord
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_member_join(self, member):
guild = self.client.get_guild(781422576660250634)
channel = self.client.get_channel(816799996279652393)
await channel.send(f"You made it {member.mention}! Welcome to **{guild.name}**, enjoy your stay 💚")
def setup(client):
client.add_cog(Test(client))
My discord server ► https://discord.gg/sfYjTSA
(If you have any questions or just want to have a chat with us)
(Some Cool Stuff)
Nertivia ► https://nertivia.supertiger.tk/
My server in Nertivia ► https://nertivia.supertiger.tk/invites/B4tMwO
Install discord.py ► pip install discord.py or py -3 pip install discord.py
Discord.py documentation ►...
Are you looking at stars?
yes?
Lol
Is that more important or the features it provides?
Imo I would go with disnake which already supports slash commands,context menus and apps
Its easy and stable
Great support team and already has an external lib which supports d.py also
And the only reason pycord has more stars than anyone is because of the owner having a big yt Channel and an already existing big discord server
I mean I'm not here to stop u, you can use pycord but Im just telling that there's better libraries out there which supports more features than the one which has more stars or is more famous
Ok, I will consider it
oh, so options are Pycord, nextcord, and disnake..
I need some help. For some reason, my bot is not responding to any commands. It starts up fine and loads cogs and whatnot, but it just doesn't register any commands. I already reset my key, any other ideas?
you sure its shows online?
Yes
I already checked wether it was running somewhere else
online/offline correspond to me turning the code on/off
yep. btw, has it worked before? like have you added something and it didn't work?
ye it has worked for months now, I haven't changed much except deleted a cog that wasn't being used.
I can't think of any reason why that was cause the flux, though.
Where are you hosting it
Hm
not sure but I think flask is a library. Where do you start and stop it?
is it locally on a command line? or do you connect to a vps or another server?
I have a local bot.py file that sets up cogs, flask server, and all that jazz, and a local bot_config file that handles imports and such
Nothing in that area has been changed.
Maybe the channel that ur using has perms for the bot not to talk
I use a permission plugin for dev tools
shows send_messages as True, and the channel has no requirements
Well I have it as Admin is True, nothing else
Uh no idea, try opening a support ticket
Alr, if anyone else knows lmk please
to where? Discord dev?
all I could think, is that maybe when you deleted some stuff, there was some indentation error or brackets that were left open. but if thats the case, it would return an error
Yeah, no errors
this is what it returns, if helpful at all
OHP i have idea that may solve
I also turned on message content intents a bit before bot went fizz.
dang still nothing
@commands.command(aliases=['avatar'])
async def avatar(self, ctx, member : discord.Member = None):
"""
Get the current avatar of your user!
"""
if member is None:
embed = discord.Embed(title="This command is used like this:
await ctx.send(embed=embed)
return
else:
embed2 = discord.Embed(title=f"{member}'s Avatar!", colour=0x0000ff, timestamp=ctx.message.created_at)
embed2.add_field(name="Animated?", value=member.is_avatar_animated())
embed2.set_image(url=member.avatar_url)
await ctx.send(embed=embed2)``` error
``` Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Kaneki-Main\bot.py", line 139, in on_command_error
raise error
discord.ext.commands.errors.CommandNotFound: Command "avatar" is not found```
anybody have ideas for some commands?
Cogs loaded and you have a setup, inherited class, and all of that?\
NASA APIs [https://api.nasa.gov]
that was unexpected
also you cant set the alias to the same name as the command
OH yeah that's it, good catch lol.
yea i changed that still didnt work
Do other commands in the same class work?@trim fulcrum
no i found this error
ExtensionFailed: Extension 'cogs.general' raised an error: CommandRegistrationError: The alias avatar is already an existing command or alias.```
...just check if anything else is named that or has that alias
nope
Apparently there is, did you reload your cog/save code?
Why are you sending code if members is None
lol i didnt save
ah
Anyone have ideas for this?
Can you show is your code?
probably have an on_message somwhere without process_commands
or message intent but i doubt it
I was about to say that
I mean there's quite a lot of it
@silent ermine
I don't think discord would like 6.4 MB of code
erm
!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.
"Be sure to add await bot.process_commands(message) inside on_messages or you'll break your commands!" - https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working
I want to point out that
@bot.command()
async def restart(ctx):
app = await bot.application_info()
if ctx.author in app.team.members:
await ctx.send('Restarting...')
print('Restarting...')
await bot.logout()
await bot.login(os.environ['token'])
is bad.
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().
Do use:
- run your bot in a process manager such as:
- systemd
- openrc (gentoo, devuan)
- runit (void linux)
- supervisord
- upstart (old ubuntu)
- docker
- manually reboot it
Do not use:
- a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
- subprocess.call (you will eat your memory up by not letting your old processes die)
- os.exec*
Kaneki Support has [<Member id=771095966060773407 name='Kaneki Bot' discriminator='5317' bot=True nick=None guild=<Guild id=895832701129601034 name='Kaneki Support' shard_id=None chunked=False member_count=106>>] in it!
@commands.command(aliases=["members"])
async def membercount(self, ctx):
guild = ctx.guild
await ctx.send(f'{guild.name} has {guild.members} in it!')```
why did i get that message
Ok, but that doesn't fix the issue.
that returns a list of member objects
how do i return membercount?
use len(guild.members)
Use len
ight
I know but I wanted to point that out
{len(guild.members)}
yeah
You don't have members intent so just use guild.member_count instead of len(guild.members)
Otherwise you will get just 1
ok
async def button(ctx):
await ctx.send("Click below Button", components=[Button(label="Button Testing", custom_id="button1")])
interaction = await client.wait_for(
"button_click", check=lambda inter: inter.custom_id == "button1"
)
await ctx.interaction.send("Button Clicked")```
this is my button code
and it says interaction failed
any help
error in your console?
yep discord-components
its interaction.respond
no respond
.
you would be using type = InteractionType.ChannelMessageWithSource
or just type=4
channel message with source is 4 right
ye
yass
How can i make mute command ?
1 , setting up a mute role for the server with send message perms off in all channels ( either manual or using bot)
2 , get the role
3 . add the role to the user
but I need to do it on every server my bot in?
Yes - you could automate adding the role though as Sarthak_ said
@slate swancan u once send me whole code with type
if you wan to have that in more than one server , you wont be able to hardcore , it needs to be done with some database , of the name of the role needs to remain Muted ( same) for all servers
the sending part ?py interaction.respond(type=4 , content= 'sus')
ok
any errors now?
also , do you have an error handler?
no errors
.
@bot.command()
async def addxp(message, amount, user: commands.Greedy[discord.Member]):
members = user or message.author
for j in range(0, len(members)):
cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)",
(message.guild.id, members[j].id, 1))
if cursor.rowcount == 0:
print(len(members), members)
for j in range(0, len(members)):
print(members[j].id)
await bot.db.execute(
f"UPDATE guildData SET exp = exp {str(amount[0])} {str(amount[1:])} WHERE guild_id = ? AND user_id = ?",
(message.guild.id, members[j].id))
cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
(message.guild.id, message.author.id))
data = await cur.fetchone()
exp = data[0]
lvl = math.sqrt(exp) / bot.multiplier
if lvl.is_integer():
for k in range(0, len(members)):
member = members[k].id
for i in range(len(level)):
if lvl == levelnum[i]:
await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
embed.set_thumbnail(url=member.avatar_url)
await message.channel.send(embed=embed)
await bot.db.commit()
@bot.command()
async def xp(ctx, user: discord.User = None):
member = user or ctx.author
# get user exp
async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
(ctx.guild.id, member.id)) as cursor:
data = await cursor.fetchone()
exp = data[0]
# calculate rank
async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id)) as cursor:
rank = 1
async for value in cursor:
if exp < value[0]:
rank += 1
lvl = math.sqrt(exp) // bot.multiplier
current_lvl_exp = (bot.multiplier * (lvl)) ** 2
next_lvl_exp = (bot.multiplier * ((lvl + 1))) ** 2
lvl_percentage = ((exp - current_lvl_exp) / (next_lvl_exp - current_lvl_exp)) * 100
embed = discord.Embed(title=f"Stats for {member}", colour=discord.Colour.gold())
embed.add_field(name="Level", value=str(int(lvl)))
embed.add_field(name="Exp", value=f"{exp}/{int(next_lvl_exp)}")
embed.set_thumbnail(url=ctx.author.avatar_url)
embed.add_field(name="Level Progress", value=f"{round(lvl_percentage, 2)}%")
await ctx.send(embed=embed)
Ignoring exception in command xp:
Traceback (most recent call last):
File "C:\Users\wolf\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\wolf\Observant Force discord\main.py", line 77, in xp
async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id)) as cursor:
File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\context.py", line 41, in __aenter__
self._obj = await self._coro
File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 184, in execute
cursor = await self._execute(self._conn.execute, sql, parameters)
File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
ValueError: parameters are of unsupported type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wolf\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\wolf\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\wolf\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: ValueError: parameters are of unsupported type
is that sqlite or aiosqlite?
Aiosqlite it seems
the paramaters to enter must be a tuple
aiosqlite
do you mean user: commands.Greedy[discord.Member] it is a list I checked
You probably just need to use a comma after your ctx.author.id
using Type()
no , the values you enter in the database
yes
( ctx.author.id , )
@slate swan my problem is in addexp cmd
if lvl.is_integer():
for k in range(0, len(members)):
member = members[k].id
for i in range(len(level)):
if lvl == levelnum[i]:
await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
embed.set_thumbnail(url=member.avatar_url)
await message.channel.send(embed=embed)
whats line 77 in your code?
rank = 1
did you add , at the end of all your sql queries?
cool
@slate swan Thanks for helping but do you have time I have one more question rq
sure ig , ill try to help
Ignoring exception in command addxp:
Traceback (most recent call last):
File "C:\Users\wolf\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\wolf\Observant Force discord\main.py", line 60, in addxp
await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
AttributeError: 'int' object has no attribute 'add_roles'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ZIV\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\ZIV\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\ZIV\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'add_roles'
2 [<Member id=555944200047296513 name='Ꮤøℓƒ' discriminator='0001' bot=False nick=None guild=<Guild id=825821295307915304 name='test' shard_id=None chunked=True member_count=6>>, <Member id=840315621073223703 name='AnimeManSad' discriminator='1457' bot=False nick="Wolf's alt" guild=<Guild id=825821295307915304 name='test' shard_id=None chunked=True member_count=6>>]
555944200047296513
840315621073223703
async def addxp(message, amount, user: commands.Greedy[discord.Member]):
members = user or message.author
for j in range(0, len(members)):
cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)",
(message.guild.id, members[j].id, 1,))
if cursor.rowcount == 0:
print(len(members), members)
for j in range(0, len(members)):
print(members[j].id)
await bot.db.execute(
f"UPDATE guildData SET exp = exp {str(amount[0])} {str(amount[1:])} WHERE guild_id = ? AND user_id = ?",
(message.guild.id, members[j].id,))
cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
(message.guild.id, message.author.id,))
data = await cur.fetchone()
exp = data[0]
lvl = math.sqrt(exp) / bot.multiplier
if lvl.is_integer():
for k in range(0, len(members)):
for i in range(len(level)):
member = members[k].id
if lvl == levelnum[i]:
await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
embed.set_thumbnail(url=member.avatar_url)
await message.channel.send(embed=embed)
await bot.db.commit()
if lvl.is_integer():
for k in range(0, len(members)):
for i in range(len(level)):
member = members[k].id
if lvl == levelnum[i]:
await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
embed.set_thumbnail(url=member.avatar_url)
await message.channel.send(embed=embed)
@slate swan this code above what giving me problems ^^^
Ꮤøℓƒ#0001
@zenith basin
guys how can we make slash commands in python
exclude discord.py
guys how can we make slash commands in python
exclude discord.py
Pls dont make duplicate messages people ignore you for that reason so please wait until someone helps you
ok
how to check if there is any type of ping in a message
try
message.mentions
ok
like if```
message.mentions in message.content:
#then the action
Thanks!
try this
if not working
dm me\
for basic ness
u can use if '@' in message.content:
It's
for mention in message.mentions:
print(mention) # This is the user that got mentioned
print(len(message.mentions)) # The number of mentioned users in the message, will be 0 if nobody got mentioned
this is pretty unecessary based on what they want
has anyone here used the roblox api if so dm me?
has anyone here used the roblox api if so pls help me.
sc = SlashCommand(bot, sync_commands=True)
If I sent an attachment, the message.content will be None right?
Pls Share Script Invite Tracker
Eye sore?
Hi ,
How can i get page name in googleserach library?
Hi i have this code where i would want to put the emoji in an embed and also let it react to to the embed so that the user can get a role with that reaction
async def embed(ctx, get):
emoji = get(ctx.message.server.emojis, name="Male"),
emoji = get(ctx.message.server.emojis, name="Female"),
Myembed = Embed(title= f"Please pick your gender role by reacting to the emoji", color=0x24045b,
description=f"Gender role")
await client.say(embed=Myembed)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\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: NameError: name 'get' is not defined```
hang on nvm i think i know the soluton
nvm
These are old stuff.. u should use client.send and not client.say and then to mention the server it's not message.server it is message.guild
i tried importing get from discord.utils but that didnt work
how did u import?
from discord import FFmpegPCMAudio
import os
from discord.ext import commands
import discord.utils
from discord.utils import get
import datetime
from datetime import datetime
import json```
```import discord.utils
from discord.utils import get```
Imported 2 times?
Also why is there a get param?
async def embed(ctx, get):
it said get wasnt defined but it should work without it since i imported get
Yes


