#discord-bots
1 messages · Page 563 of 1
no ig
you need to enter the path there , so it would bepy bot.load_extension('commands.somecommands')
it prints the function name as you can see before, _run_event is a task where dpy dispatches events, etc
it doesnt print the func name ig, otherwise it would be task not _loop
@tasks.loop(seconds = 50)
async def task(self):
self.task.get_task().set_name(f'PlayerCountTask-{self.count}')
ok so how can i make it loop through the files and load them?
commands must be a list ( called array in js) with all the cog paths
its just like ```py
commands = [ 'cog1', 'cog2']
for file in commands:
the line you already have```
Did not help. It gives an error like this:
Traceback (most recent call last):
File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\Дмитрий\AppData\Local\Programs\Python\Python35-32\Scripts\pip.exe\__main__.py", line 5, in <module>
File "c:\users\дмитрий\appdata\local\programs\python\python35-32\lib\site-packages\pip\_internal\cli\main.py", line 57
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
but i dont want to do that tho.. i dont want to hard code it
you need to install it first
its a problem in your code now
like example
commands
|help.py
|ping.py
then it will loop through the files in commands so 2 files and load them
or wait
hi i want to make it when an user joins it gets a role but its not working. do you know why ?
@bot.event
async def on_member_join(member):
role = get(member.guild.roles, id="902559208422137897")
await member.add_roles(role)
well you can use a for loop to loop through "commands" and load the cog
https://github.com/Rapptz/discord.py/blob/master/discord/ext/tasks/__init__.py#L151 it seems to return this. Try printing i.get_coro().__class__ and see what it prints
IDs are integers not strings
uhh
how can i do that
its still not working
show me what u did
you can use os.getenv
@bot.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, id=902559208422137897)
await bot.add_roles(member, role)
for commands in os.getenv('commands'):
#loading stuff```
for filename in os.listdir("./folder"):
if filename.endswith(".py"):
bot.load_extension(f"folder.{filename[:-3]}")
``` literally what everyone uses
why is it bot.add_roles()
just member.add_roles(role)
there we go
Is it possible to fix this error?
halp me it's been going on for 2 days
guild is none
how to fix
its... still not working
@bot.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, id=902559208422137897)
await member.add_roles(role)
its guild.roles not server.roles
wait @jovial osprey does your bot have member intents
None in message.guild means that it's in DM
you mean this ?
so I muted in a DM
oops thamk
yes
still not working
hm
have you set the intents in your code?
what intents
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
the one in the codeblock
wait, I didn't mute them in the DM, I muted them in the server. It assigned the muted role to the spammer, but didn't mute them. Why?
hello?
anyone
?
heloooooo
I just realized, its not code, its something else
it works now, thanks
because they still have other roles with permissions
wait, so how do I fix it
f'**Tasks:**\n{newline.join([i.get_name() + ", " + i.get_coro().__name__ + ", " + str(i.get_coro().__class__) for i in asyncio.all_tasks(self.bot.loop)])}'
Tasks:
Task-609, _run_event, <class 'coroutine'>,
PlayerCountTask-42, _loop, <class 'coroutine'>,
Task-610, _run_event, <class 'coroutine'>,
Task-2, runner, <class 'coroutine'>
you need to store those roles, unassign them and assign the muted role, and on unmute, you need to assign those roles back
they are coroutines
but the spammer had no other roles
he only had muted, and then lost the muted role afterwards.
I see, are the role permissions correct?
yes, the permissions were correct.
.run(token) ones?
I see
idk im looking at the tasks
ah
what is the difference between runner and run event
oh
i think _run_event is a cog listener
cus i have 2 of those
so it seems that the task was created with the _loop function, so you would never get the task's name
how fix
how can i give a cog listener a task name
idk ;-;
well how do i get_task a listener really
how can i color code an embed?
like i dont get the color code stuff
i know hex but that doesnt work
It does
Can u show me what you did?
you sure?
yes
becasue if i can get the task i can do set_name() on it to give it a name
ok, let me re-phrase. I'll use pseudo
@client.event
async def on_message(message):
if spam_count > 5:
mute(message.author)
asyncio.sleep(10)
unmute(message.author)
can you turn that into python? (or how)
can you show me your actual code?
I think its because its a string
- Its supposed to be an integer.
- Remove the hash from the code and replace it with
0x(should be0xDC143C)
ok
okie
yay ty
i tested with on_message and on_command_error listeners, 1 event comes from on message the error one doesnt do anything
by default ig bots have a runner task and a _run_event task idk what they do
I changed it to banning them then unbanning them, but I think they would be angry at me for doing that
whats the problem
@velvet tinsel its because discord.utils.get() is sending None as the response
also why 2 variables just use one
like icy said is the channel a guild channel? or a DM channel?
so I remove discord.utils.get()?
runner is bot.run and _run_event is for dispatching your events, it is created everytime you make a listener I think
no ig
@velvet tinsel this the problem
remove only the second one
ok
^
and 1 more?
is there a way to rename those tasks
My english is breaking 🥲
i have those listeners in separate cogs, unloaded them one at a time to see their effect on the 4 tasks
after unloading the on_message one, one of the 4 tasks dissapeared
but unloading on_command_error didnt change anything
yea, i think _run_event should only be called once (at bot.start)
rename listeners?
yes
(embed) Go to youtube
and youtube should be clickable and should redirect to https://www.youtube.com
How do I do this?
you cant, listener isnt a task
hyperlinks?
yesh
I fixed it, but it's sstill not muting
I have a server for it, do you want me to send an invite?
yay my bot now runs 24/7 🙂
I tried
where did you put it?
description
what
its either ctx.message.author.add_roles or discord.Member
!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.
how to i mention the author of the command?
ctx.author.mention
thx 🙂
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
role = discord.utils.get(message.author.roles, name='Muted')
await discord.Member.add_roles(message.author, role)
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(role)
now it's returning with
AttributeError: 'NoneType' object has no attribute 'id'
why doesn't anybody know this 😢 stack overflow hates me as well, plus the community is toxic (like, very very toxic)
hello guys tell me how to auto-delete a message after a certain amount of time
I legit was pondering this question for 2 days, 2 of the people helping gave up on me and stack overflow muted me for 7 days because of some toxic person
pls help me
I'm legit on my knees
full traceback?
Ignoring exception in on_message
Traceback (most recent call last):
File "[_________]", line 343, in _run_event
await coro(*args, **kwargs)
File "[___________]", line 42, in on_message
await discord.Member.add_roles(message.author, role)
File "[______________________]", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
role is None
so how do I fix
discord.utils.get(message.author.roles, name='Muted') this returned None
i think you mean message.guild.roles
ok
sorry I didn't see that 😛
wait why is he smiling
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\[___]\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\[________]\PycharmProjects\Dave\main.py", line 41, in on_message
role = message.guild.roles(message.author.roles, name='Muted')
TypeError: 'list' object is not callable
😫 python hates me
discord.Member.add_roles lol
that doesn't work I tried
role = discord.utils.get()
I meant, thTs the wrong way lol
you're contradicting blanket, and plus if I do that it would have an error
Nvm, why did I even say that 🤦
yes what you said was correct
Nono, I am talking about the discord.Member.add_roles() thing
bruh
its not over?
nope
can I just spoonfeed
yes please
you need to pass in message.guild.roles into the first argument of discord.utils.get
No thanks
I don't care anymore
bruh, I've tried for 2 days
learn more python
^ its like isinstance() but for finding something
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I have lessons for python, what do you think I'm doing
its not like isinstance?
then study them, im p sure discord.py isn't a basic python lesson
I did pass in message.guild.roles
I asked everywhere
Hey @jovial osprey!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
it is i just included the parentheses
how is discord.utils.get like isinstance
again, learn more python
Is nobody gonna help me
I'm sure you don't have enough OOP knowledge so just go back and learn some python ig
I already did
bruh
discord.py isn't something a beginner should do in a learning phase
this doesnt relate to oop at all though
Yes, and it returned with an error
it does
which error
in their code they did discord.Member.add_roles(message.author, ...)
Well he tried discord.Member.add_roles
which clearly shows lack of knowledge
Which shows that he doesn't know basic OOP
why did they use the class
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\[___]\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\[________]\PycharmProjects\Dave\main.py", line 41, in on_message
role = message.guild.roles(message.author.roles, name='Muted')
TypeError: 'list' object is not callable
How to change embed colour?
i told you how to do it
I went through an entire book of python
your code was right the first time
i have another problem, i want to make it that when i press a button i will get a role but it doesnt works it says: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
heres the code ```py
@bot.command()
@commands.has_role("「💻」 Bot Developer")
async def skin(ctx):
embed = discord.Embed(
title = "Vytvorenie skinu",
description = "Toto je popisok.",
colour = discord.Colour(0x80ff80)
)
embed.set_footer(text="bot made by samuelll hehe")
embed.add_field(name="Meno poľa", value="Niečo 1", inline=False)
await ctx.send(embed=embed)
await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Len testujem buttny", components=[Button(style=3, label="Default Button", custom_id="button")])
res = await bot.wait_for("button_click")
if res.channel == ctx.channel:
member = res.guild.get_member(res.user.id)
await member.add_roles(902869731223150642)
await res.respond(
type=InteractionType.ChannelMessageWithSource,
content=f"{res.component.label} has been clicked!"
yes and I did exactly what you asked
set color attribute of embed to a different color, it's just an attribute
ok where is the updated code
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
role = message.guild.roles(message.author.roles, name='Muted')
await discord.Member.add_roles(message.author, role)
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(role)
right
its all right
right, exaclty what i said
I removed everything that caused an error, apart from message.guild.roles
yeah, i told you to call message.guild.roles
@velvet tinsel i dont see anything wrong here though
no I didn't update that
anything wrong
But when I do color=009900 it give error
do a hex number
0x
color=0xhex
your code was already correct earlier
wait I'm trying something
Ohk
color=0x009900 I guess
pls bal
It works now thanks
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
role = discord.utils.get(message.guild.roles, name='Muted')
await discord.Member.add_roles(message.author, role)
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(role)
would this work?
bsdk bal
?
you're in the wrong server
try it and see
use message.author LIKE I SAID your code was ALREADY correct
dank memer
I did
wrong server bro
No dank here
but keeping discord.utils.get?
yes
doesnt matter https://www.toptal.com/developers/hastebin/kusososudo.py was already correct
I literally dont see any errors
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\\PycharmProjects\Dave\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\\PycharmProjects\Dave\main.py", line 42, in on_message
await discord.Member.add_roles(message.author, role)
File "C:\Users\\PycharmProjects\Dave\venv\lib\site-packages\discord\member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
in that code whatsoever
again
It is possible to use Json on Python?
No, I wanted it to mute the person. What I'm saying is that it doesn't.
yes
?? they need the role from the guild first in order to add it
yes.
they already did that
mutedRole = discord.utils.get(guild.roles, name="Muted")
that one is wrong
but I had to remove the second mutedRole variable
was wrong?
that doesnt affect anything your code was still correct
How to make a condition that if A person in a particular channel has sent a message, then the bot will forward this message, and then delete the author's message
What have you tried yet
No error, but it doesn't mute
Show your code
Guys I have code
bruh
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False,
read_message_history=True, read_messages=False)
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(mutedRole)
You literally did remove_roles
too many things
How can it mute if you remove role
did u add the role first?
after 10 seconds
I think it was the wrong code I sent
!d discord.Member.add_roles just use this
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.
Apparently I don't see any add_roles
Can anyone review it
sure
^ @velvet tinsel
Can I send the replit link or the code itself
It's the same result
code I guess
What does invoke_with_command do?
@velvet tinsel
try using ```py
i added it, still no response
show code
invoke_without_command when set to True will try to invoke the subcommand first, if no subcommand found, invoke the group command, when set to False, it will invoke the group command, along with subcommand when it found one
!code
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.
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False,
read_message_history=True, read_messages=False)
await message.author.add_roles(mutedRole, reason="spam")
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(mutedRole)
Is there an error though
try debugging the command
no
I debugged it, it still doesn't mute me
Not working guys
just do ```py
print("hello")
!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.
Are you server owner/have admin rights?
I used a test account that wasn't the owner/admin
How to make sure that if a message is sent to the chat, then the bot sends it to another chat, and the first message is deleted?
So do you get the role?
yes
Then it's about role settings
then use hastebin
!paste it here
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.
message is a discord.Message object, if you want to check where a message is from, use message.channel, and also if you want to compare them use ==
if message.channel == channel1
With python i can do a custom help command like:
Did you add muted role perms to channels?
?
yes
what do I do now?
How to forward a message sent by the author?
!customhelp
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Do in channel they can only read message history/view channel. Do same to role perms settings
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
that's the discord.Message repr, if you want to get the content just, message.content, and send that instead
thanks you so much
Good to go
Anyone saw this
isnt related to discord-bots
No
now my entire message history between the bot and me is stop spamming! stop spamming! stop spamming!
why
Just a noob thing
Yeah
I had no idea more than that
Can't we run the code directly in hastebin
If you see this keenly you can understand
bruh
uh.. you can just use pass instead of putting None
thats basically my bot rn
OHHHH
Thank you
ok no need to share that.
nothing happened
apart from the bot saying Stop spamming!
what do I do
should I give up on the muting thing
Nah keep it going
Success isnt always easy
How to make it so that if the message is more than 1024 characters then not to forward it?
len function on the message content
message.content
What isnt hard in life
Why is that?
your supposed to do embed=ur_embed_variable
nobody can help/helps me
wahh
I'll stop the muting thing
how do u use author's pfp in embed
I didn't quite understand
like this?
embed=emb
!d discord.Embed.author
property author: _EmbedAuthorProxy```
Returns an `EmbedProxy` denoting the author contents.
See [`set_author()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.set_author "discord.Embed.set_author") for possible values you can access.
If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
Do it yourself you dont need anybody but yourself
!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**.
no spoonfeed
k
ohhhh, yea thanks @slate swan@boreal ravine
ok
Exactly
what'd would spoon feed mean?
like not giving them solution rather hints?
yes
Isnt spoodfeed like giving snippets to someone or giving him the solution
yes
I tried already
it is
So both
Try harder🤷♂️
Doesnt look like you did
Try way harder than ever before
doing your best sometimes takes alot of time yk 
ok
Success takes time
And hard work
ah i got the my answer
what is it?
I am like stuck
I want to make a feature for my discord bot which tells you the server info
I dont know how to do it
like no-of members / channel etc?
how
i want like this
post code and error
u can use uptimebot
uptimerobot
@leaden jasper heroku 
@rain ridge pls help
# doing some detecting...
@client.event
async def on_message(message):
guild = message.guild
counter = 0
with open("spam_detect.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
# tells them to stop... and mutes them.
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False,
read_message_history=True, read_messages=False)
await message.author.add_roles(mutedRole, reason="spam")
await message.author.send("Stop spamming!")
await asyncio.sleep(10)
await message.author.remove_roles(mutedRole)
its not 24/7
and there is no error, it just doesn't do anything
Yes it is
Not the best for bots thats more for websites and other stuff
@rain ridge
its not really plus its not reliable
just tell if am right
Still works for being free
@leaden jasper
Not reliable
It's the best free option
uptimerobot is wdym
Yes ofc
May not be but still when comparing the free options you have, heroku tops with ease
For sure
u have a counter for everyone tho
Can't compare to an actual payed vps tho
I've never used uptime before but for being free heroku is the best for me
Why not use json
so what do I do
Yeah
Why are so many people using .txt files instead of json 😭
You can use a raspberry pi correct?
Or just a normal dict, that works too 💀
track the count for users in a dictionary
Me with a rpi4 😏
yaml 🙄
Yeah a rpi is good too, although a vps tops it both in cost and reliability (depending on your internet connection and rpi version)
but if I did that my pc would explode
Yeah
can anyone help me
how many users are u tracking
You're clearing it from time to time tho? Why would it explode
ok
raspberry pi 4 is best, just make sure to get a cooling case as it gets really hot
Yes ofc if your gonna run it like a server 24/7 it is recommended
ok
yup
do u need number of members
@client.command()
async def create_channel(ctx,msg1):
guild = client.get_guild(guild_id)
channel = await guild.create_text_channel({msg1})
whts wrong here?
yes
Or just put it in your freezer(jk dont do that)
@client.has_any_role(886987124623151176) @commands.cooldown(1, 60, commands.BucketType.user) @client.command()
lmao i mean-
do you have server info code

!d discord.Guild.member_count
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
no but u can find one by someone else on github probably
.
i cant
?
thats why i cam here
Came*
No spoonfeeding
yes
ok
Hi guys! Does any1 have a good intro to discord bots python resource online?
like where do i start
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Discord selfbot made with Python using discord.py. Contribute to appu1232/Discord-Selfbot development by creating an account on GitHub.
FileNotFoundError: [Errno 2] No such file or directory: 'BlockInfo.json'
What happen here?
yes but idk where the code is
ur script cant find that file ig
But that on same directory as python file
Have you learned the basics of python and have you read the api reference?
line 38 downwards
u dont need to copy everything just pick what u need
A good VPS is more reliable and cheaper lmao
Isnt a rpi like 40bucks? And you have your own mini computer
Yeah but you have the bills
i didnt say i just host on my rpi tho-
Both electricity and internet bills
i also do alot of things on it
cheap
wait
A vps would be way cheaper
Like ovh for exmaple, you can pay 4 bucks monthly for a really good VPS
I mean its a mini computer it doesnt take that much and you can run other stuff on it to like a minecraft server
I mean yeah you could
Also more reliable because there's more chances of your electricity going down rather than the vps's providers
self bots are against tos lmfao
@commands.has_any_role(886987124623151176)
How can I create an error message for the users who do not have this role?
This is just a name
Yeah ofc but i really depends on the vps
Not actually selfbot or userbot ig
Yeah
It depends if it has like a heavyweight package or a premium one stuff like that but if you have a rpi it can be a server just for you that you dont need to pay each month or worry about your money in your paypal or stuff like that
You do have to pay each month tho? 🤨
Both good but i prefer a rpi
There's electricity and internet bills that the rpi increases
can someone help me with how i would check a users role then display it inside of an embed? cant figure it out=
Yes ofc but it really depends on your electricity bill your internet speed and where you live
Yeah
You can iterate over the user's roles
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
Idk i prefer a rpi cuz its fisical and other stuff
It may look cool and fun but a vps is more practical, reliable and cheap
Yeah
Physical* u mean? 😂
@commands.command(aliases = ['q'])
async def quote(self , ctx , message: discord.Message):
a = message.jump_url
b = message.content
c = message.channel.name
d = message.created_at
embed = discord.Embed(timestamp = ctx.message.created_at, color = message.author.colour , description = "{}".format(b))
embed.set_author(name = str(message.author) , icon_url = message.author.avatar.url)
embed.add_field(name = "Link" , value = '[Springe zur Nachricht]({})'.format(a) , inline = True)
embed.add_field(name = "Geschrieben am:", value = "**<t:{}:{}>**".format(int(d.timestamp()), "F"), inline = True)
embed.set_footer(text = "#{}".format(c))
return await ctx.reply(embed = embed)
If I try to get the message content of an embed it only respond with 'Springe zur Nachricht' and 'Geschrieben am' and not with the content in general. How could I do that?
English isnt my native language either so i get confused sometimes
And where you can see all time formats by type - And where you can see all time formats by type - %x | %H:%M
how do you tell if a dictionary contains something?
if key in dict
Why are you using on_message wtf
Do yourself a favor, and use commands
It's gonna make your life a ton easier 
got a question about checking what role a user has then printing it in an embed in #help-cookie if anyone wants to swing by
dose anyone know the announce command code
bad tutorials
Hey is anyone able to help me with a question?
?
I have a command that splits the message content , however if someone doesnt type the command and another word like (!command word) it crashes. How would I get it to ignore the command if it doesnt have the second word
sorry if that was worded poorly lol
hm
instead of using discord.Client use commands.Bot and use bot.command instead of on_message
well you can use if not to check if an argument wasnt passed then you can return ig
where
in your code
i don't have the link to where it's showcased how to use commands but it's in the docs if you look for it
Who knows where my mistake is
@commands.command(name= "мемчик")
async def mem(self, ctx):
des = random.choice(["Я пришёл разнести вас по личным причинам.", "Неправильный не я… Неправильный весь этот мир.", "Я просто подвигами маюсь.", "Выбор – это всегда только компромисс или эгоистичный ход в своих интересах. Только так.", "В конце концов, весь мир вращается вокруг меня!", "Терпеть не могу пороховой огонь, он понятия не имеет о хороших манерах.", "Если вам нечего делать, то не надо делать это здесь!", "Дураки любят высокие места.", "Сейчас мы покажем, на что способны… БЕЖИМ!!!", "Мы дойдем до самого конца! А потом еще куда-нибудь…", "Враньё – это путь к популярности."])
embed = discord.Embed(title="Цитата:" , description=f"{des}")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/animememes/random.json') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
That is because slash is meant to work with a bot not a client.
yes this is api reddit
it's too big but that's what causes the error
I'm telling you it doesn't affect this command
I'm importing
Then don’t ask for help if you can’t show
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
import aiohttp
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
The rest of the code is commands that work fine
How to take JSON Value into embed?
Example
"name": "This is Title"
I want the value of name is imported to Embed Title
What’s the error?
value_for_name_key = thejson['name']
error
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 211, in mem
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
TypeError: list indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\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\Baraban4ik\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\Baraban4ik\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: TypeError: list indices must be integers or slices, not str
good thanks
And where to find it user_agent
@slate swan
And how to get it out then
reddit = praw.Reddit(client_id='CLIENT_ID HERE',
client_secret='CLIENT_SECRET HERE',
user_agent='USER_AGENT HERE')
Here you threw me the first 2 I led
How can I get another bots embed and get my bot to relay that embed
Would I use get_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.
with this Message object, you can do
yourMessageObjectName.embeds[0]
can someone explain why
@commands.command(name="profile2")
async def _profile(self,ctx,member: discord.Member=None):
if not member:
member = ctx.author
pfp = member.avatar_url
membermention = ctx.author.mention
ages = ['15', '16']
memberroles = [role.name for role in member.guild.roles]
age = [i for i in ages if i in memberroles] # contains all "age" roles
if not age: # if they dont have any age roles
text = 'No role'
elif age[0] == '15':
text = '15 years underage'
elif age[0] == '16':
text = '16'
embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
embed.set_thumbnail(url=(pfp))
embed.add_field(name="Verification", value="Verified", inline=True)
embed.add_field(name="Age", value=text, inline=True)
embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
with open('blacklist.json', 'r') as file:
file = json.load(file)
if str(member.id) in file:
embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
await ctx.send(embed=embed) ```
doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
it always just displays "15 years underage"
is there any way to create an economy bot that stores value for a person, or does that require dicts and databases?
I think it requires dicts and databases
writes when sending a meme
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
do I store it in a .txt file?
what
definitely not
code
async def meme(self, ctx):
reddit = praw.Reddit(
client_id='A5HNPvyhKCAj5l64h8R9RQ',
client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
)
memes_submissions = reddit.subreddit('memes').hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
await ctx.send(submission.url)
Ok. Do dicts work as well?
what is your question
is this a mistake or not
Like, balance[user] = money or something?
yes, I know what a dict is
ok, so only databases work
sure , but it will reset when the bot restarts
I'm saying it's nothing powerful nor easy to use
right?
thats why I said to store it in a .txt file
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io. is not blocking , but PRAW itself is , we highly suggesting using asynchronous PRAW 🙏
it is powerful.
or I make a new python file and never run it but store everything in it
and you would have to read the whole file everytime?
or a python file
json would be suggested instead , a database could be better tho
txt files are bad to use for a discord bot economy system
you can try sqlite , its easy believe me
just 4 or 5 statements and logic
json isn't a database either
but it would crash my computer
that's the exact opposite of what we suggest
storing that many data on my computer would send it alight
json is made for static data
its better than a txt file
or would it not?
Yeah but how do I do that
read the docs
someone said use a txt file ?
everything's better than a txt file
i've never gone against that ?
sorry, it was because I was using one for an anti-spam bot
i have database for 60+ guilds stored ( prefixes and some channel ids ) and the file size is just around 10-12kb , how can that crash your device
we don't talk about that, it totally did not work and I totally didn't lose all my braincells
because they told them to use json
well ,if they were forced to pick between txt and json, i'd say go with json
Oh, it was because someone previously said that
oh
nobody's forced peepoCry
we'll never know
And a small question, can you create buttons for games using discord.py?
even companies wouldn't force anybody to use a json as a db
iirc they have been implemented
there's no case where you can use txt and json but not sqlite , its an internal python library
ok-
yes , if you use the beta version
what do you mean, beta version?
yep beta version
it's called beta but imo it's pretty stable
it aint available on pypi yet so pip install discord.py wont install it
oh wait nevermind
you need to use git
yes
I don't understand how to install asyncpraw in my code
reddit = asyncpraw.Reddit(
client_id='A5HNPvyhKCAj5l64h8R9RQ',
client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
)
memes_submissions = reddit.subreddit('memes').hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
await ctx.send(submission.url)
they did
I looked at the documentation and didn't understand
not sure , but everything other than slash commands was already implemented
import it?
just do
random_meme = random.choice(memes_submission)
to get a random meme and post it
I initially used the usual praw.
B everything worked but wrote that it was better to use asynchronous praw
Can I make a pokemon bot using python? coz in youtube everybody is showing withs javascript.
Yes
you can make anything
except voice receiving
you would have to make the fork first
can u help me making the bot?
if you use this code then writes this:
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
reddit = praw.Reddit(
client_id='A5HNPvyhKCAj5l64h8R9RQ',
client_secret='fZTDnK8A0BpA8r_zzEjNzmp1Ky0C_w',
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.1.684 Yowser/2.5 Safari/537.36'
)
memes_submissions = reddit.subreddit('animememes').hot()
post_to_pick = random.randint(1, 10)
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
await ctx.send(submission.url)
Sure dm
ok
help
Wdym?
can someone explain why
@commands.command(name="profile2")
async def _profile(self,ctx,member: discord.Member=None):
if not member:
member = ctx.author
pfp = member.avatar_url
membermention = ctx.author.mention
ages = ['15', '16']
memberroles = [role.name for role in member.guild.roles]
age = [i for i in ages if i in memberroles] # contains all "age" roles
if not age: # if they dont have any age roles
text = 'No role'
elif age[0] == '15':
text = '15 years underage'
elif age[0] == '16':
text = '16'
embed=discord.Embed(title=f"**Roleplay Finder**", description=f"**Discord User**: {membermention} | {member} ", color=0xffffff)
embed.set_thumbnail(url=(pfp))
embed.add_field(name="Verification", value="Verified", inline=True)
embed.add_field(name="Age", value=text, inline=True)
embed.add_field(name="Literacy", value="Semi-Lit", inline=True)
with open('blacklist.json', 'r') as file:
file = json.load(file)
if str(member.id) in file:
embed.add_field(name="__BLACKLISTED__", value="This user is blacklisted.", inline=False)
await ctx.send(embed=embed) ```
doesn't change the text in the embed no matter if i have no roles, the 15 role or the 16 role
it always just sends the first possible value
e.g 15, then if i edit 15 to a random number like 99 it'll send 16, then if i edit both to random numbers it says
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
im trying to mention a random member but the bot just mentions itself
@bot.command()
async def randommember(ctx):
await ctx.send(f"{random.choice(ctx.guild.members).mention}")
should i do this?
for member in ctx.guild.members:
if member == user.bot:
#do something
intents
if you don't have guild member intents then the only thing ctx.guild.members returns is yourself
Isnt intents for ban and kick commands?
Or is intents just permission to see other members
guys, I created buttons (version 2 of the Danny library) and I created them in a separate file, but how do I respond to these buttons in another file?
- import this class
- make view
- and how i can respond to buttons ?
pls help
there are multiple intents
guild, guild members, message intents, presence intents, etc...
while True:
interaction = await self.client.wait_for("button_click")
if interaction.custom_id == "colours":
this doesnt work
make the view by instantiating the class, and you override the callback coro within the subclass
So its like kinda what i said?
class ShopView(discord.ui.View):
"""
This view creates shop buttons"
"""
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Colours",
custom_id="colours",
style=ColorsConfig.colours, emoji="🎨")
async def colours(self, button: discord.ui.Button, interaction: discord.Interaction):
pass
i made button
right
you're already responding to it
async def colours() is what's called when the button is pressed
async def server_shop(self, ctx):
view = ShopView()
edit_embed = discord.Embed(
description="Select the category of products that you would like to see",
color=0x2f3136
)
edit_embed.set_author(name="💳 Server Shop")
edit_embed.set_footer(text=f"Requested by{ctx.author.name}", icon_url=ctx.author.avatar.url)
embed = await ctx.reply(embed=edit_embed, view=view, mention_author=True)
while True:
interaction = await self.client.wait_for("button_click")
if interaction.custom_id == "colours":
embed2 = discord.Embed(
title="Colours:",
description="``1.`` <@&840311378455429122> ``800``:coin:\n``2.`` <@&840312261939560508> ``800``:coin:\n``3.`` <@&840312664911249438> ``800``:coin:\n``4.`` <@&840313421764886539> ``800``:coin:\n``3.`` <@&840312664911249438> ``800``:coin:\n``4.`` <@&840313421764886539> ``800``:coin:\n``8.`` <@&850108513514684416> ``800``:coin:"
)
await embed.edit(embed=embed2)
this is another file
how i can resons
ty
help then pls bruh
to respond to interactions, put the code within the async def colours()
replace your pass with the callback logic
delete it ?
no, that's the coro that's called when the button is clicked
so put your code that you want to run when the button is clicked inside it
class MyView(discord.ui.View):
def __init__(...):
super().__init__(...)
@discord.ui.button(...)
async def myCallback(...):
print("User clicked a button")
for a more complete example, you should check out the /examples/views folder on the github page
okey
thank you!, ill try do smth
but still i need respond to button in a another file
you can just import the class and initialise it
how bro?
show example please)))))
class MyView(discord.ui.View):
def __init__(...):
super().__init__(...)
@discord.ui.button(...)
async def myCallback(...):
print("User clicked a button")
from buttons import MyView
async def someCommand(...):
view = MyView()
await ctx.send(view=view)
well that's awesome then you know how to do it
but in my command i made embed
i want when we click on button - edit this embed
yeah pass that into the view class
class MyView(discord.ui.View):
def __init__(..., new_embed):
super().__init__(...)
self.new_embed = new_embed
@discord.ui.button(...)
async def myCallback(...):
await interaction.response.edit_message(embed=self.new_embed)
your main file would look like so:
from buttons import MyView
async def someCommand(...):
embed = discord.Embed(...)
view = MyView(new_embed=embed)
await ctx.send(view=view)
you get the point
new_embed - where i need create it, above await interaction.response.edit_message(embed=self.new_embed) ?
how do i download a users profile picture?
it doesn't really matter where you make it
as long as you pass it into the view class
!d discord.Asset.save
await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this asset into a file-like object.
@commands.command(name="Backgrounds", aliases=["bgs"])
async def backgrounds(self, ctx):
x = '\n'.join(str(y) for y in options.keys())
y = '\n'.join(str(x) for x in range(len(options)))
embed = nextcord.Embed(description=f"{}")
embed.set_author(name=ctx.author.name + "#" + ctx.author.discriminator,
icon_url=ctx.author.avatar.url)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed, allowed_mentions=am)
How do I do it so it display like this in the description
1 word
2 word
not really related, but instead of doing
ctx.author.name + '#' + 'ctx.author.descriminator
you can do
str(ctx.author)
Thx worked
oh yea, thanks
@sick birch your code works! ty!, but if u dont mind - can i ask u a few questions more ??
How do i delay a command? I tried
time.sleep() and it just pauses the whole scirpt im trying to pause the command only
import asyncio await asyncio.sleep(3)
It onlt delays the command correct?
It delays a async command?
And comes again right
yes.
Thank you very much
Yeah go ahead
Hi, is there a way to create a text channel just for a specific person that asked for it and noone more ?
Use permissions to exclude everyone else out besides the author
does anyone have a code for it ? i cant find any tutorials
I have made one but it's closed source
So?
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
thanks for atleast some info
Hm
Ahh ye overwrites as well
!d discord.TextChannel.overwrites
@jovial osprey
I guess it's this one
thanks
hi guys, I am working on some bots and noticed there are threads since some time, did anyone try those already?
discord.py does not support it directly I guess, it is on feature branch
I think it will come with realease 2.0
I am wondering what is the best way to update my library with this feature branch, do I simply checkout the branch and merge and then switch lib files?
https://discord.com/developers/docs/topics/threads
https://github.com/Rapptz/discord.py/tree/feature/threads/discord
this is a pert of TextChannel?
Why am I recieving this error? I swear this is correct
@commands.command(aliases=["bal"])
async def balance(self,ctx, user: discord.Member = None):
if user == None:
bal_em = discord.Embed(title = f"{user.mention}'s Balance", description = f" {user.name} has a balance of",colour=0xFFA500)
await ctx.send(embed=bal_em)
else:
bal_em = discord.Embed(title = f"{ctx.author.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
await ctx.send(embed=bal_em)
bal_em = discord.Embed(title = f"{user.mention}'s Balance", description = f" {user.name} has a balance of",colour=0xFFA500)
AttributeError: 'NoneType' object has no attribute 'mention'
Hi so I have gthis cmd
cur.execute(f'''INSERT INTO banlist (user_id) VALUES ({user}) (reason) VALUES ({reason}) (moderator) VALUES ({ctx.message.author})''')
``` or more line but it **always** gives me a syntax 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 "main.py", line 107, in ban
cur.execute(f'''INSERT INTO banlist (user_id) VALUES ({user}) (reason) VALUES ({reason}) (moderator) VALUES ({ctx.message.author})''')
sqlite3.OperationalError: near "(": syntax error
this is why
What does that mean?
what do you mean by cooldown?
After the command is executed it cant be used in a certain time aka a cooldown
can someone help?
Alr
Read the traceback
Do not use f string!
And I would recommend aiosqlite instead of SQLite3 module.
ok i asked in #databases
client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
client.counter += 0.02
client.this_dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(30))
client.counter = 0
@client.command()
async def checkbac(ctx, *, arg : discord.Member):
await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[ctx.author.id]}')
if ctx.author.id not in client.dict:
return await ctx.send('0.00')
huhhhhhhhhhh
bal_em = discord.Embed(title = f"{user.name}'s Balance", description = f" {user.mention} has a balance of",colour=0xFFA500)
AttributeError: 'NoneType' object has no attribute 'name'
This is working
but for some reason, everyone has the same BAC level
prob messed up dict
there won't ever be the 2.0 release, dpy is discontinued since months ago
:(
Yeah i used that thanks
Did anyone use discord.Threads?
you can use disnake, it's a fork of dpy so it has dpy's 2.0 syntax, and it's by far the most promising and most stable with the latest features compared to any other fork
It is a new feature
user is None
What are you using to store these things?
dict
nvm brain fart
i created a global dict
Ok, do you think that's a good idea?
wel to store the value yea
Have you heard of a database?
database stores it forever thi
i want the avlues to reset after 30 mins
so wouldnt dict be the best option?
docs pls
Use tasks.loop to delete it after every 30 mins, I would suggest using postgres as ur db
ok ill check it out thanks
but just wanted to know: what exactly is the error in the code?
There is no error, its working fine, also showing the BAC, but the bac for everyone is the same
im guessing it has to do with ID
What database should i use?
mongodb for nosql and postgresql for sql
Thx
client.this_dict = {}
@client.command(pass_context=True)
async def drink(ctx):
client.counter += 0.02
client.this_dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(30))
client.counter = 0
@client.command()
async def checkbac(ctx, *, arg : discord.Member):
await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[ctx.author.id]}')
if ctx.author.id not in client.dict:
return await ctx.send('0.00')
@kindred epoch
ideas for commands??
hm
what does it return?
.
everyone has the same counter
if i do !drink it goes up by 0.02, i do !drink again now its 0.04
what type of a bot do u have?
multi functional
i do !checkbac @slate swan it says i have BAC of 0.04
so i dont care about the command xd
everyone used the command same amount of times
no
thats the probllem
even if somoene has never done !drink, they'd still have the same BAC as me
everyone in the server has the same counter
no idea tbh
ok
if you look at your code, that makes sense. you need multiple counters. try using a dictionary instead with each user ID as a key. then you can do client.counters[ctx.author.id] += 1
oh I see
client.this_dict = {}
client.this_dict[ctx.author.id] = client.counter
would basically end up with {'myID' : 0.02}
oh I see why
yep but everyone has the same counter
even if someone has never done that drink cimmand
you are referencing ctx.author.id every time, not the user you are mentioning's ID
holy
just replace ctx.author.id with member.id
await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.this_dict[arg.id]}')
^
however
even i mess up like that
you should put if arg.id not in client.this_dict: return await ctx.send('0.00')
first
^
yeah, forgot lol
OHH WAit i understand now
arg.mention is a string
it was giving the BAC of the person running the command
it has no ID
oh wait i got it il fix it now
you could clean this up a lot more. you don't need to sleep in your first command
ah, I guess you're going for some effect of it returning to 0 like real life? lol
??
yea
after 30 mins it resets and goes back to 0
How to make command/on_message bot
but only we as admin can command the bot not member.
is that possible?
@client.event
async def on_member_join(ctx, member):
global hasloo
channel = discord.utils.get(client.get_all_channels(), guild__name=f'{ctx.guild.name}', name='【✅】weryfikacja-1')
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
await channel.send(f"**Wyślij komendą** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` why no working?
on_message bot?
@client.command(aliases=['stats', 'bi', 'info'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def botinfo(ctx):
allmembers = 0
uptime = datetime.datetime.utcnow() - start_time
uptime = str(uptime).split('.')[0]
for guild in client.guilds
allmembers += guild.member_count
guilds = len(list(client.guilds))
before = time.monotonic()
ping = (time.monotonic() - before) * 1000
embed = discord.Embed(title=f"**__alone__**", color=color)
embed.add_field(name="** name:**",value=f"{client.user.name}", inline=True)
embed.add_field(name="** guilds:**",value=f"{guilds}", inline=True)
embed.add_field(name="** users:**",value=f"{allmembers}", inline=True)
embed.add_field(name="** ping:**",value=f"{int(client.latency)}ms", inline=True)
embed.add_field(name="** uptime:**",value=f"{date_time}", inline=True)
embed.add_field(name="** discordpy version:**",value=f"{discord.__version__}", inline=True)
embed.set_footer(text=f"requested by: {ctx.message.author.name}")
await ctx.send(embed=embed)```
Why is this sending 3 times
on_member_join only takes 1 arg, which is member
its look like this.
async def on_message(message):
if message.content == "1":
await message.channel.send('test')
^^^
Because you are iterating through client.guilds
If you want it to only run once get rid of the for-loop and dedent the code inside of it
theres nothing called on_message bot, anyways, best is using the command decorator, and it would be easier to check if the user has admin perms or not.
@client.event
async def on_member_join(member):
global hasloo
haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
haslo2 = 5
hasloo = "".join(random.sample(haslo,haslo2))
await client.get_channel(828011225292079124).send(f"**{member.name}, użyj komendy** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` this no working too ]
ok, ok how i can do that. imean
make command but only we admin can use thats command how ?
@commands.has_permissions(adminstator=True)
i got this
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
TypeError: Invalid permission(s): adminstator
this chart is… questionable
Nevermind Its just typo sorry, it working now!
how i can make a field for a userinfo that shows the guild permissions? only the highest one, using user.guild_permissions
anyone familiar with heroku?
but idk how to do it
IOError isn’t raised when trying to open a file that doesn’t exist, FileNotFound gets raised
ig its outdated now 😔
or i could be wrong
can someone help?
f
was my favorite chat 😔 so much sarcasm in the title
user.top_role.mention
but that shows like: administrator
yeah what do u want to show
it doesn’t, it mentions the top role
i mean this @slate swan
its from another bot idk how to do it, but i only want the highest one
wdym highest one
so role permissions or user permissions
theres no highest permission
Is it possible to get the id of the message that a bot sends so I can edit it later on
administrator its the higher one
pretty sure there's a way to do that without id if i remember
not my bot XD
oh? that sounds good
wait
ctx.message.edit? maybe idk ill look in docs for u hang onm
user permissions i think?
okay thanks 😄

!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
if i set the content to nothing then will it be deleted?
i don't know i don't use it, maybe @hasty iron knows.
no, and again that wouldn’t work
oh ok
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
thats how you delete a message
await ctx.message.delete()
whats the * a placeholder for