class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
#discord-bots
1 messages · Page 523 of 1
how can i add this reactions to the message (embed) that the bot will send?
embed = await ctx.send(embed=embed)
await embed.add_reaction('✅')
await embed.add_reaction('❎')```
Thanks
How do you get the message id of every message for a mod log?
how to remove all of 1 emoji on a post
so if there are 10 emojis wipe the given one
anyone have a method for this
?
How can you just remove all of 1 reaction on a post.
like if there are 20 of 1 reaction how can I remove only those 20 and leave the others
I found some code for a personal use music bot, but the play function doesn't work and it keeps giving an exception. anyone see what's wrong?
how would i make it so instead of this only using one server/guild, it uses all of them that it's in?
guild = bot.get_guild(guildid)
do you have ffmpeg
in it's directory
yes in bin in the environment
go ahead
wr
this is just renaming the embed object to a message object. It will work but is bad practice as it can get confusing.
msg = await ctx.send(embed=embed)
emojis = ['✅', '❎']
for emoji in emojis:
await msg.add_reaction(emoji)
or just
msg = await ctx.send(embed=embed)
await msg.add_reaction('✅')
await msg.add_reaction('❎')
import functools
import colorama
import requests
from colorama import Fore
import threading
import discord
from discord.ext import commands
token = ""
# headers will go here
sers = []
intents = discord.Intents.all()
client = commands.Bot(command_prefix=";", help_command=None, intents=intents)
class fabz:
def nick(guild):
try:
requests.patch(
url=f"https://discord.com/api/v9/guilds/{guild}/members/botidwillgohere",
json = {"nick": "sussy bot"},
headers=headers)
print(f"changed bot nickname in {guild}")
except:
print(f"Cannot change nick name in {guild}")
pass
@client.event
async def on_ready():
for guild in client.guilds:
sers.append(guild.id)
for guild in sers:
try:
yummy = functools.partial(fabz.nick, guild)
threading.Thread(target=yummy).start()
except:
pass
client.run(token, bot=True)
it print changed nickname but doesnt change the nickname
How do you get the message id of every message for a mod log?
i still need help with this if anyone can help lmao
you need a command to get all your server guilds?
i dont understand what u r asking
i have a command and i want it to get members from all server guilds
if that makes sense
like the total number or literally every single member
bot.users
hi i want my bot to run a command i've made on start, how can i do that?
@bot.event
async def on_ready():
uh ik that
kekw
wouldn't you just type in the name you defined for the command
oh hmm
well you wouldn't have it as a command you would have it as a function but why not just paste the command code in on_ready?
How do you make a footer like this? Like would I add another text=“” in the footer?
\n
Traceback (most recent call last):
File "C:\Users\marva\Desktop\python bot\main.py", line 14, in <module>
client.run(config.TOKEN)
NameError: name 'client' is not defined```
import config
class Myclient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('=hi'):
await message.channel.send('hello!')
client = MyClient()
client.run(config.TOKEN)```
im need help
is this the main file for the bot?
yes
none of this is right, why are you subclassing discord.Client?
class MyClient(discord.Client):
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')```
it is written in the manual
A basic bot would look like this
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run("TOKEN")
the one you're talking about is not for bots
this is discord.py in github
I know but your code is not for discord bots
thanks
help
me
not really
i just want to make sure
is using discord.py on your own account against tos
cus i made a command for purging my messages and archiving groupchats / channels
yes self botting is against tos and can get your account deleted
would this be right? im trya do this embed.set_footer(text=f"Author: {message.author.id}", text=f"Message: str{message.id}")
How do I change the new profile settings like the "About me" or the pfp banner for a bot
For the about me, go to the dev portal and go to your bot app, you’ll see a description that you can add
So the About me is just the desc
Yeah
hi how can i check that if author top role is higher than target top role
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
you can check if its > the target's top_role
if author.top_role > target.top_role:
Can someone help
If this is a command you can use the has_permissions decorator
i use if too
You don't have to if this is in a command otherwise, you can manually check if author.guild_permissions.kick_members is True
and i want to do these statement
you can't use the same kwarg twice, it should be in 1 string
Then how should I do it ?
then check the guild_permissions of the bot's member object instead
embed.set_footer(text=f"Author: {message.author.id} | Message: str{message.id}")
Okay
but can you give me the code
like if bot.guild_permissions.kick_members is True
???
well, is bot defined?
@bot.command
Why do you want to use If statements instead of the decorators
to send message to the member to know which error occured
That sounds like a job for error handlers
It will let you do the same thing in a much neater way
instead of checking for each condition in a chain of if-statements
how do i make an embed that has the discord random colors implemented have the same colors as another embed that also has discord random colors?
Just assign the first random color to a variable
How could I make a command to say the number of lines in a JSON file.
No you would do it like this embed.set_footer(text=f"Author: {message.author.id}\nMessage: str{message.id}")
What do you mean by "hidden messages"?
Oh idk how to get it like that
Woah
Tanks
main()
File "run.py", line 347, in main
finalize_logging()
File "run.py", line 179, in finalize_logging
dlh.setFormatter(logging.Formatter('.'))
File "/usr/lib/python3.8/logging/__init__.py", line 580, in __init__
self._style.validate()
File "/usr/lib/python3.8/logging/__init__.py", line 433, in validate
raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
ValueError: Invalid format '.' for '%' style```
How could I remove that line it sent?
What account does that generate?
No self if it's not in a class.
And also hidden messages work only with interaction replies, not normal meessages.
how does that matter, i just need help removing a line
What line? And also, it does matter.
!rule 5 Some accounts generators break this rule.
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
It is not cracked accounts
The line it takes idk how to explain it
The message it sends?
Well, it's taking it from a TXT file, and then sending it
I want it to remove the line it takes from the TXT file
Can I see the _getline() function?
https://stackoverflow.com/questions/4710067/how-to-delete-a-specific-line-in-a-file I think this should help.
You loop through each line and if the line is equal to the line you want to delete, then don't write it.
Alright
Basically, re-write every line in your file except the line you want to delete.
@bot.command()
async def add(ctx,member: discord.Member = None):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send("how much bananas do you want to give")
message=await bot.wait_for('message', check=check)
if not member:
member = ctx.author
await open_account(member)
user = member
users = await get_bank_data()
await ctx.send(f"you have given the user {message.content} bananas")
users[str(user.id)]["wallet"] += message.content```
how do i fix this error?
!e
names = ["Seif", "Scoopy"]
new_names = []
for name in names:
if name == "Seif":
continue
else:
new_names.append(name)
print(new_names)
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
['Scoopy']
What does users[str(user.id)]["wallet"] return?
Ah, there's 2 problems.
I believe it returns an int, and message.content is a str.
!e
num = 1
num += "1"
print(num)
@dapper cobalt :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: unsupported operand type(s) for +=: 'int' and 'str'
that's uh
stuff to do with my json file that contains 'balances' for users
oh ok ty
Also, in your check, add and message.content.isdigit().
where at
In your check.
wait my bad misread it
It will then check if the message.content can be converted into an int.
Since if it tries to int("s") for example it's going to raise an error.
@dapper cobalt I can't even figure out how to start ngl
def _getline(command: str):
with open(f"./{command}.txt", mode="r", encoding="utf-8") as file:
lines = file.readlines()
value = random.choice(lines)
for line in lines:
if line.split("\n") == value:
continue
else:
file.write(line)
file.close()
if command == "unban":
del lines[lines.index(value)]
new_file = open(f"./unban.txt", mode="w+", encoding="utf-8")
for line in lines:
new_file.write(line)
new_file.close()
return value
This should work.
Command raised an exception: UnsupportedOperation: not writable
Print value.
int(message.content)
Okay, so I got past that one error, but now when I run the command, it clears the whole TXT document and then sends
Command raised an exception: IndexError: Cannot choose from an empty sequence```
Code
```py
def _getline(command: str):
with open(f"./{command}.txt", mode="wb+") as file:
lines = file.readlines()
value = random.choice(lines)
for line in lines:
if line.split("\n") == value:
continue
else:
file.write(line)
file.close()
if command == "unban":
del lines[lines.index(value)]
new_file = open(f"./unban.txt", mode="wb+")
for line in lines:
new_file.write(line)
new_file.close()
return value
ModuleNotFoundError: No module named 'discord.interactions'```
im having this error even though I installed it via command line
I have ran pip install discord.interactions and pip install discord-interactions on 5 occasions but still when I try run it, it still says I do not have the module
does anyone else have this issue?
I would like to detect a link without the https://
like for example starting with www. or invites from discord without https, such as discord.gg/ , dsc.gg/ , dc.gg/
with regex I only got the links that started with https://
regex.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.content.lower())```
Can someone help me?
def _getline(command: str):
with open(f"./{command}.txt", mode="r+") as file:
lines = file.readlines()
value = random.choice(lines)
for line in lines:
if line.split("\n") == value:
continue
else:
file.write(line)
file.close()
if command == "unban":
del lines[lines.index(value)]
new_file = open(f"./unban.txt", mode="r+")
for line in lines:
new_file.write(line)
new_file.close()
return value```
Why is this removing the one line, but duping the others
You sure this isn't an account generator?
it is, but not for cracked accounts or anything like that
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
You literally cheat in mc. I doubt you care about cracking accounts
ok
Still would break Mojang tos
It's not even anything about MC LOL
Okay?? LOL
Like I said, it is a account generator but doesn't break ANY tos of any service.
Account generator for what?
Why do I have to provide information to you?
how about minecrafts tos?
holy shit are desperate are you degens
???
nice
it is
It's an account generator
NFA = non full access
Literally what I said
omg no way u figured that out!!
we didnt need to
literally battle.net accounts that I made and verified myself, doesn't break tos.
I wouldn't suggest you ask for anymore help with this project
cool I guess
I don't own it??
Ok bro
@final iron give invite
@honest wing
Check his YouTube channel
He removed it
actual informant holy shit
Lemme DM you video
Let's keep it on topic buddy
cringe
👍
lmao
cute dog
@dapper cobalt I wouldn't suggest you help @honest wing if he dms you
why are you being cringe
My DMs are off anyways. And I don't accept friend requests from people I don't know. Though, thanks for the warning.
Reasons
i hope you die in whatever ur favorite one life game is
how would one go about sending an PIL.Image object through discord?
right now i've sort of got it working, it sends the image but it shows up as a downloadable file, not the actual image
That's a bit broad
IKIK
But THATS the only API that im having confusion with
i even read the docs
but s t i l l
What are you having confusion with specifically
how do i get the content
the gifs
I can do the random and sending part
But how do I get the gifs with my api key and search term and limit
I can't help you specifically with that but it's probably a popular API so someone will come eventually
anyone knows a way to use purge to delete certain number of messages from only one user?
someone is
hmph
maybe do an if?
Idk tbh
how tho?
ohk
but purge doesnt really work that way....
if i add an else statement, will it work?
what are you trying to do ?
are you trying to do this ?
If the user who is running the command doesn't have kick members perm then the bot should send some message ?
yes
Instead of permission you should write has_permissions
oh then you can do this
if ctx.message.author.has_permissions.kick_members:
#Rest of code (when the command user has kick members perm)
else:
#Rest of the code (when the command user doesn't have kick members perm)
Btw you can use error handlers as well
ye
It’s best to use the has_guild_permissions decorator
oh
There isn't really a telegram-bots channel here?
ok
i dont think so
didnt work
oh eah
yeah*
Its discord
Discord likes to annoy
so most of the attributes are never available
did anyone add snekbox in their bot?
¯_(ツ)_/¯
wut
i dunno anything about snekbot
it's the module python bot uses to EVALUATE the codes
how do I install it
and how to import
idk, i am asking same
member has no attribute has_permission. so what does it have?
i think it is if ctx.author.has_guild_permission.kick_members
idk really
How do I make the actual channel mention tag show up cuz it’s just showing the channel id
i d k
I don't think you can mention in titles, so you will have to just use name. Otherwise try it in description
You need to run it within docker, then it has an api you can call with aiohttp.
@gloomy quest @slate swan
lol would be very tiresome
I mean if you want it, thats how its built
Although in saying that, you could likely request agaisnt the one pydis runs
oh
import requests
import discord
from discord import ext
from discord.ext import commands
import asyncio
token = ""
client = commands.Bot(command_prefix="$")
@client.event
async def on_ready():
print("UP AND RUNNING")
print(client.user.name)
@client.command()
async def tracker(ctx):
embed = discord.Embed(title="1️⃣ - 1st | 2️⃣ - 2nd", description = "Vote accordingly")
one = '1️⃣'
two = '2️⃣'
msg = await ctx.send(embed=embed)
await msg.add_reaction(one)
await msg.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=2.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
except:
print("error")
client.run(token)
Uhm in the reaction, user = await client.wait_for("reaction_add", timeout=2.0, check=check)
await ctx.send("You choose 1") and await ctx.send("You choose 2")
i am gettting red wavy lines under the await of these ^^
am i doing anything wrong
i see u
@commands.command(aliases=['cl', 'purge', 'delete'])
async def clear(self, ctx, times: int, member:discord.Member=None):
if ctx.author.guild_permissions.manage_messages:
await ctx.message.delete()
if member is None:
await ctx.channel.purge(limit=times)
embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
await embed_message.delete(delay=5)
else:
def check(msg):
return msg.author == member and msg.channel == ctx.channel
await ctx.channel.purge(limit=times, check=check)
embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted from {member}",
color=discord.Color.random()))
await embed_message.delete(delay=5)```
why isnt the member purge working?
Well, what does it currently do? How far does it run? Does it error?
Can you add some print statements and see what it does
Can you put links in embed titles?
Like [Text](httls:\\google.com)
bc that isnt working for me rn
u can do title=title, url=url to do that
oh, thanks!
u can in desc
where?
how would i create a channel thread using my bot?
In your code
ok i changed it a bit
@commands.command(aliases=['cl', 'purge', 'delete'])
async def clear(self, ctx, times: int, member:discord.Member=None):
if ctx.author.guild_permissions.manage_messages:
await ctx.message.delete()
if member is None:
await ctx.channel.purge(limit=times)
embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
await embed_message.delete(delay=3)
else:
await ctx.channel.purge(limit=times, check=lambda message: message.author == member)
embed_message2 = await ctx.send(
embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
await embed_message2.delete(delay=3)
else:
await ctx.send(
embed=discord.Embed(title="Stop right there!", description="You require the Manage Messages permission.",
color=discord.Color.green()))```
@valid perch
Which messages deleted..
Theres two
Your 'waiting' within a function that never gets called lol, fix your indentation
nothing gets deleted
I meant code wise. You have two different sections which could output the same thing
Weird, should work
Has the person you are trying to delete sent a message within the last (times)
times is the amount of messages to look through, not amount to delete from the person
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
i want !purge 4 @gloomy coral to delete my last 4 msges
Likely gonna have to implement the search logic yourself ig
i did....
mMmm
Itll be expensive but you could loop over channel history and do checks yourself
hmmm there has to be a better way tho
Given the information you've given me to work with, no. Since idk what that is in the slightest and unfortunately I can't read minds
lol nice
@commands.command()
async def akinator(self,ctx):
await ctx.send(embed=discord.Embed(title="Akinator is here to guess!",description="'Y' is Yes, 'N' is No, 'P' is Probably, 'B' is Back",color=discord.Color.random()))
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["y", "n","p","b"]
try:
aki = akinator.Akinator()
q = aki.start_game()
while aki.progression <= 80:
await ctx.send(embed=discord.Embed(title=q,description="Your answer:(y/n/p/b)",color=discord.Color.random()))
msg = await self.bot.wait_for("message", check=check)
if msg.content.lower() == "b":
try:
q=aki.back()
except akinator.CantGoBackAnyFurther:
await ctx.send(discord.embed(title=e,color=discord.Color.random()))
continue
else:
try:
q = aki.answer(msg.content.lower())
except akinator.InvalidAnswerError as e:
await ctx.send(discord.embed(title=e,color=discord.Color.random()))
continue
aki.win()
await ctx.send(embed=discord.Embed(title=f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?(y/n)\n{aki.first_guess['absolute_picture_path']}\n\t",color=discord.Color.random()))
correct = await self.bot.wait_for("message", check=check)
if correct.content.lower() == "y":
await ctx.send(embed=discord.Embed(title="Yay\n",color=discord.Color.random()))
else:
await ctx.send(embed=discord.Embed(title="OOF\n",color=discord.Color.random()))
except Exception as e:
await ctx.send(e)```
let me guess, akinator has no type Akinator or something?
akinator.Akinator() refers to your function. Since you defined it as akinator. Rename it or rename the import
Unless that isn't your issue, in which case do more then simply paste code, cheers.
!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.
no i imported it, its looping many times
i did tht?
You tell it to loop until its over 80?
It sends the code in your while loop, who'd have figured. Yes error pelase
What check would I put if my meme command started spamming memes whenever I did the command?
Code?
@commands.command()
async def meme(self, ctx):
reddit = praw.Reddit(client_id='COhMnzSDUwpfkHKVhvcHnQ',
client_secret='PCKVk0yiqq6FQvfxXsdi0lKGEWBuBQ',
user_agent='bobert')
message = ("Loading meme...")
await ctx.send(message, delete_after=3)
memes_submissions = reddit.subreddit("memes").hot()
post_to_pick = random.randint(1, 100)
all_subs = []
for i in range(0, post_to_pick):
submission = next(x for x in memes_submissions if not x.stickied)
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url=random_sub.url
embed = discord.Embed(
title=f"__{name}__",
url=submission.url,
colour=discord.Colour.random(),
timestamp=datetime.utcnow()
)
embed.set_image(url=submission.url)
embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url)
embed.set_footer(text="Here is your meme!")
await ctx.send(embed=embed)
@dapper cobalt
Why are you iterating through it?
return after sending the embed.
okay so it stopped but now its just sending the same meme
it will spam lol u looped the code
@dapper cobalt
but now its sending the same meme whenever i do cmd
!d random
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.
Similar names: django.random
what am i supposed to do .-.
await ctx.guild.create_custom_emoji(name=name, image=emoji.url_as('png'))```
It makes this error, no idea how to fix it
```py
TypeError: url_as() takes 1 positional argument but 2 were given```
d!help
please ping me if someone is willing to help
url_as takes kwargs
Like everything in this library
So do format="png"
Instead of just "png"
kwargs*
I just noticed that my ascii command isn’t working but every other command is, can someone help?
https://hastebin.com/pareviquki.py
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.
Might help given formatting issues
like when i do *ascii dk it doesnt send anything back
Chur, I think the issue is your if
When it should be checking < (less then)
Currently your command only does things if the text is longer then 2000
Also your indentation on the last line is wrong, since its the same as the return
No worries
ahh! thanks!
print(res)
date_time = res['datetime']
datetime_time = datetime.strptime(raw_time, "%Y-%m-%d %H:%M:%S")
time = str(datetime_time.strftime("%I:%M %p"))
date = str(datetime_time.strftime("%d %B %Y"))
embedVar = disnake.Embed(title=f"Weather details of {location}", description=date, color=bot_embed_color)
embedVar.set_thumbnail(url="https://i.pinimg.com/originals/26/be/b0/26beb09153b8df233d82e66bef3edfbb.jpg")
await ctx.send(embed=embedVar) ```
Can someone tell me the error here
whats the error tho
:troll:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 410, in _run_event
await coro(*args, **kwargs)
File "main.py", line 31, in on_command_error
raise(error)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/bot.py", line 1220, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 899, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 179, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'datetime'
The api works
Ik that
That's not the issue
ur accessing something in the api that doesnt exist? idk
hm
hm so the command works (including the datetime thing) but the error still pops up?
The command doesn't work
try printing ```py
res['datetime']
The same output
I tried it
Looks like it can't pull it from the json
No idea why not
Someone please help
Have you even tried to print the output you get from the request
AttributeError: 'PartialEmoji' object attribute 'url_as' is read-only```
code:
```py
em = emoji.url_as='png'
await ctx.guild.create_custom_emoji(name=name, image=em)```
It's a method not an atribute that you need to use
how to give permissions to someone ?
There is no average. It depends on the VPS you get, it's performance, the usage of the bot, etc. etc.
oh okay
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
I can't install dislash
-ERROR: Could not find a version that satisfies the requirement dislash (from versions: none)
-ERROR: No matching distribution found for dislash
Uh discord settings? Xd
Lmao
get a link with the proper permission integer from the developer portal oauth tab
btw which is better? discord_slash or dislash
bc I thought dislash was better and it turns out discord_slash had much more stars
like x3
._. I wonder why ppl are still using dpy its not being worked on itll prob be outdated in a year or two
And start breaking
what are the other options?
bc the dpy replacements are still being made, it's not possible to move to a new package atm
I don't think anyone has reached to a full fledged battle tested package
Well u can try some forks but they are not good i dont wanna do shameless self promo so i aint gonna mention mine but there is another one called disthon i checked the source its not great, mine is not ready to use yet but in a week or two it will be kinda ready
i cant start my bot anymore, can someone help?
root@vServer:/home/PyBots/QEmotes# python bot.py File "bot.py", line 26 async def on_ready(): ^ SyntaxError: invalid syntax
Code:
async def on_ready(): print('---------------------------------------') print('Bot: {}'.format(bot.user.name)) print('Bot-Status: Online') print('Made by Qrime') print('---------------------------------------') bot.loop.create_task(status_task())
async def on_ready():
print('---------------------------------------')
print('Bot: {}'.format(bot.user.name))
print('Bot-Status: Online')
print('Made by Qrime')
print('---------------------------------------')
bot.loop.create_task(status_task())
this has no syntax error
thats why i am here :((
import platform
import sqlite3
import asyncio
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="e/", intents = discord.Intents.all())
bot.remove_command('help')
# -----------------------------------------------------------------------------------------------------
# DATABASE
# -----------------------------------------------------------------------------------------------------
conn = sqlite3.connect('db_QEmotes')
sql = conn.cursor()
# -----------------------------------------------------------------------------------------------------
# BEGIN OF CODE
# -----------------------------------------------------------------------------------------------------
# STARTUP
@bot.event
async def on_ready():
print('---------------------------------------')
print('Bot: {}'.format(bot.user.name))
print('Bot-Status: Online')
print('Made by Qrime')
print('---------------------------------------')
bot.loop.create_task(status_task())```
Yes sir
!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.
I have a js file it has some functions that I want to import to a py script how would I do that also its in the same directory
And what does it give
Js and py are 2 different languages
ty i forgot how to do this
ok so you can't import ?
Yes
Np
ok 😢
but can't you use Js2Py
Anyone knows where my mistake is? im getting syntax error
#discord-bots message
Bad argument
Converting to "int" failed for parameter "pep_number".
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
Those are no less than scams they only work for a set of code they are designed to convert not what ever, things work differently
Why is your output in bytes? (See the b prefix)
ok 😢
can you tell me?
if i would know i wouldnt ask :v
like where is the error at
also can't you just do js to json
ah u mean that i was confused sorry
thank you
@tawdry perch
in putty on linux server:
root@vServer:/home/PyBots/QEmotes# python bot.py File "bot.py", line 26 async def on_ready(): ^ SyntaxError: invalid syntax
Bro u sure u know how languages work and what is js, json and py
Json is data
js is a programming language
py is a different programming language
json is "javascript object notation", u can call it a data object for js and u can also load json strings in python and dump them
me trying so hard but yet nothing also yeah pretty much I have to do everything in python
root@vServer:/home/PyBots/QEmotes# pip install asyncio Command 'pip' not found, but can be installed with: apt install python-pip root@vServer:/home/PyBots/QEmotes#
Install pip it literally says it there lol
lmao i did it didnt work now it works with that command
maybe i had typo
lmao
¯\_(ツ)_/¯
didnt fix
Hmm
Indent?
Indent doesn't give syntax error
Hmm no
Sometimes just taking a code away with ctrl x, ctrl s, ctrl v. It may fix it.
It's simply not a supported Python version
Oh.
how do i uninstall python on linux, i did purge but it still says its installed
Why you use python 2?
It's per default installed
nvm found the mistake
Install better version of python as well
Ohh I thought they were still stuck with syntax error
They are.
And that's why they need to update Python
As already said above multiple times
I did not see that, my bad
it is always giving me the 2.7 python version :/
how to delete all roles of a server?
Loop through Guild.roles and use .delete() on each
for roles in message.guild.roles:
await roles.delete()
``` not working :/
Define 'not working'
it is showing invalid role
Invalid role?
yes
Maybe show the error
:/
Because you can't delete the default role (Guild.default_role)
Add if statement to see if role is default role
if roles == message.guild.default_role ?
Try it and see

You could have just done py for role in message.guild.roles[1:]:
It saves u from using an if statement
True. Since the default role is the first in the guild's roles list. Means that its index number is 0.
File "C:\Users\marva\Desktop\python bot\main.py", line 10, in <module>
@client.event()
NameError: name 'client' is not defined```
from discord.ext import commands
import config
bot = commands.Bot(command_prefix="$")
filtered_words = ["gay"]
@client.event()
async def on_message(msg):
for word in filtered_words:
if word in msg.content:
await msg.delete()
@bot.command()
async def ping(ctx):
await ctx.reply("pong")
@bot.command()
async def hi(ctx):
await ctx.reply("hello!")
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member} was kicked!")
bot.run(config.TOKEN)```
im need help
guild.roles also includes the @ everyone role
Already solved ^
Don't copy paste, for you it's @bot.event
As you never defined any client variable
TypeError: event() missing 1 required positional argument: 'coro'
async def on_message(msg):
for word in filtered_words:
if word in msg.content:
await msg.delete()```
Please read what I wrote
Where do you see any ()?
Just a helpful tip, add a return or break after await msg.delete(), because since ur looping, the first word could be in the content of the msg. the msg is then deleted, but since its a loop it checks it again, the message has already been deleted, and you'll end up getting a NotFound error
I'd break, not return
i mean...doesnt really matter unless theres code after the for loop
Probably want commands to work
thanks
Although I hope the command names are not in the swear words list 
async def ping(ctx):
await ctx.reply("pong")
@bot.command()
async def hi(ctx):
await ctx.reply("hello!")
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member} was kicked!")```
Yeah
Don't forget to add await bot.process_commands(msg) at the end of your on_message event
well , using a list for bad word detection aint really a good idea , like it can be easily bypassed
and what do you offer me?
Use AI
or something like the Soundex algorithm
Although there will be quite a lot of false positive
i don't know how make ai or algorithms
i need help i want when my bot send a message add a reaction
The message sent returns a discord.Message object, which has an add_reaction method.
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
How do I do live timer using discord.py without making the bot sleep
@lyric needle help pls?
Deleting messages, kinda cringe 
can someone give me an example of using try except for sending a response for a command
try:
except author missing permissions:
Simply make the error happen
Then you get the error (e.g. CommandNotFound)
And you can do except <error>:
i tried ```py
@commands.slash_command(
name="announce",
description="Announce something to everyone via the bot"
)
@commands.has_permissions(manage_guild=True)
async def announce(self, interaction,
channel: disnake.TextChannel=Param(description="The channel in which the announcement is to be sent"),
message: str=Param(description="The announcement that is to be sent")
):
try:
try:
embed=disnake.Embed(description=message, color=disnake.Color.blurple(), timestamp=interaction.created_at)
embed2=disnake.Embed(description=f"Announcement sent to {channel.mention}", color=disnake.Color.green(), timestamp=interaction.created_at)
embed2.set_author(name=interaction.author, icon_url=interaction.author.display_avatar.url)
await channel.send(embed=embed)
await interaction.response.send_message(embed=embed2)
except commands.BotMissingPermissions:
await interaction.response.send_message(f"Something went wrong. Try checking if I have permissions to send messages in {channel.mention}")
except disnake.ext.commands.MisingPermissions([disnake.permissions.manage_guild]):
await interaction.response.send_message("You can't use that", ephemeral=True)
but it doesnt work
except disnake.ext.commands.MisingPermissions([disnake.permissions.manage_guild]):
over here, disnake == discord
it still doesnt work
Without ()
yeah that doesnt work either
Because your code doesn't throw this exception
@commands.slash_command()
@commands.has_permissions(manage_guild=True)
async def cmd(self, ctx):
try:
await ctx.send("Hello")
except discord.ext.commands.MissingPermissions:
await ctx.send("error")
it still shows the error
MissingPermissions
which lib
disnake
Forbidden is raised for Missing Permissions issue
How do I make my bot send prefix when bot is pinged like @bot
and not @bot how are you?
?
@slate swan like this...
if ctx.message.content == <"@your bot id">:
#show prefix
I tried
Not at all
message.content
Yeah nvm
1: Content
2: <> go in the "
3: It can also start with !
I tried but it didn't work
Can bot.get_guild return None?
It can be <@!id> and <@id>
Or just 404 Not Found
So check both
Whats the difference?
!
Phone and computer
Nicked and not nicked
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
I didn't quite understand
If it's sent via phone
There's a !
If the user is nicked and you mention it
There's also a !
oh
the mentions in message.content you get always is in <@!> format tho
@slate swan another solution..
use a condition...
its working now
Cool
I added a !
How to change volume with discord.VoiceClient
@slate swan can the guild obj return None?
Is it that hard to read?
Ok!
Thanks
is there a way to get all cooldowns ?
@client.event
async def on_message(message):
if message.content==f"<@!{bot_id}>" or message.content==f"<@{bot_id}>":
try:
em=discord.Embed(title="My prefix is `{prefix}`", colour=discord.Colour.random())
await message.send(embed=em)
except commands.MissingPermissions:
channelid = message.channel.id
await message.author.send(f"I need **Administrator** permissions in <#{channelid}>")```
Message has no attribute 'send'
@slate swan send it to the channel of the message
trying
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
And don't ask the users to give the bot admin permissions for sending an embed
A bot never needs admin permissions if managed correctly
I made my bot ask admin perms so that it can access every channel
A bot shouldn't be given admin permissions
also I changed it to message.reply
mmm
It just needs embed permissions though to send the embed
That's my point.......
How can I get channel?
Do you know it's ID?
Yes.
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Thanks
do you guys know any fun stuff i can do with my bot
i just casually use it now to send images
What
how make command clear?
you wanna clear a command?
no, I want to make a command that will delete messages
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
you can use that and use limit to make a clear command
thanks
Is my code right?
@bot.event
async def on_member_remove(member):
for channel in member.guild.text_channels:
await channel.send(f"{member.guild.name}! {member.mention}!!")
You might not want to send a message in every channel...
api abuse
Kk
why it doesnt send the message
?
Remove the , at the end of set_footer
And you can just do ctx.send instead of ctx.channel.send
and ctx.user doesn't exist, for you it's just member (like your parameter name)
Hey quick question I’m doing checks and the user needs to mention a channel how would I get the channel from the message content
it should be member.name at ctx.user.name
also why r u using msg = await ctx.channel.send(embed=em)
Just ctx.send is enough in that place
🦜
Don’t do the comma and also don’t do “ctx.channel.send” it’s ctx.send
Also bots don't require admin perms
ye ik
It's not the bot
i saw it now
It's for the user
about the perms
its ban_members = True
Hey quick question I’m doing checks and the user needs to mention a channel how would I get the channel from the message content
I could really use some help on that one if you guys don’t mind
again it doesnt send the message
Do you have any errors?
no
Do you have an on_message event?
nope
well
you still have ctx.user
In the set_footer
And you don't need to add msg= await....
As you don't do anything with the variable afterwards
its {member.id}?
Yus
like this?
Yes
it works
tysm
No problem :p
Although you should check why you don't get any errors in the console
You should get errors if you haven't made an error handler that ignores everything
probably on_command_error event
guys i whenever i use discord.ext.tasks where i have used open() for text files, all the code before it keeps getting spammed even if the interval is set to 8 hours. and doesn't do what my open() was supposed to do. anyone knows why?
how do i get the timezone?
of what
Show code
okay one min
async def on_message(self, message):
msg = message.content.lower()
localdate = datetime.date.today()
obgend = datetime.date(2021, 11, 13)```
my code, localdate come from the american timezon since my bot is hosted in america, i wanna convert it to my timezone
But what do you plan on doing with that?
Depending what you do it's not needed
async def on_message(self, message):
msg = message.content.lower()
localdate = datetime.date.today()
obgend = datetime.date(2021, 11, 13)
surgeryend = datetime.date(2022, 1, 12)
medicineend = datetime.date(2022, 3, 13)
cmend = datetime.date(2022, 5, 12)
electivesend = datetime.date(2022, 5, 27)
casualtyend = datetime.date(2022, 6, 11)
ophthalend = datetime.date(2022, 6, 26)
entend = datetime.date(2022, 7, 11)
orthoend =datetime.date(2022, 8, 10)
pediatricsend = datetime.date(2022, 9, 14)
if msg == "posting":
if localdate < obgend:
def obg(localdate, obgend):
return (localdate - obgend).days
days = f"{obg(obgend, localdate)}"
if days == 1:
await message.reply("Your Next posting `Surgery`, starts tomorrow.")
else:
await message.reply(f"Current Posting: `OBG`, {days} days to go.")```
But don't forget you can use Discord's timestamp not have to get the time difference manually
async def get_source():
print('passed to get source')
return 'flwfkn'```
```py
class Doc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.scraper = Scraping(self.bot)
self.local_cache_download.start()
def cog_unload(self):
self.local_cache_download.cancel()
@tasks.loop(hours=8)
async def local_cache_download(self):
if ...:
else:
print('called thos')
source = await get_source()
file = open('__cache/docs.txt', 'w')
file.write(source)
file.close()```
this is what happening in console:
Ready!
passed to get source
called thos
passed to get source
called thos
passed to get source
called thos
passed to get source
called thos
passed to get source
it spams it at random times
Can u ss cus I’ m on mobile and It’ s hard to read
Also use with statement to open file
i cant, the content of if is very long
Ok then
wait, i gotta do something about it
U started it wrong
?
it waits till the bot is ready,
@local_cache_download.before_loop
async def before_local_cache_starts(self):
await self.bot.wait_until_ready()```
yeah ik
then it works.
if i remove open everything goes fine
async or normal?
same thing happens,
with open('__cache/docs.txt', 'w') as file:
file.write(source)
file.close()```
Run a debugger
my code doesn't give any error
Ik, just run a debugger and out a breakpoint at the start of task
And see what happens
ok one sec
this debugger suck,
Exception has occurred: ImportError
attempted relative import with no known parent package
File "C:\Users\User\Documents\GitHub\simple-disnake-discord-bot\cogs\docs\_cog.py", line 3, in <module>
from ._scraping import Scraping```
my code is working fine tho
hlo
It works?
it doesnt give me relative import errors
Code?
@commands.command()
async def unban(self,ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split()
for ban_entry in banned_users:
user = ban_entry.user
if (user.na, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')```
Dont watch lucases tutorials
XD
why not
^
oh
Try async with
but how do i fix it
learn python and OOP
you'll fix it yoursef
ok
LMFAOOO
Use diff method for unban command
i did
which method
Stack Overflow
I need an efficent discord.py command for unban users by their tag, not their name and discriminator. how i can do?
This is the code that I made and it works with *unban name#1234.
@client.command...
didnt work
oo ok thanks
I need to get what the user mentions a channel in chat. For more context:
Put print statements in diff places
yeah, i was doing everything else so quick and then this stupid bug came up
I just don’t know how to get the channel ID to send the message to
i did in all possible places
!d discord.Message.channel_mentions
A list of abc.GuildChannel that were mentioned. If the message is in a private message then the list is always empty.
if i use open() it just starts spamming the code above open and doesnt process open statement
I think this is from stack lmao
how to make a command to change the bots prefix? I'm using discord.ext
Idk bro, It’ s weird af and I dont have computer to try it rn
U gotta store prefixes in db
Then use get_prefix method to get the orefix
oh
Prefix
This is from lucas
idk this guy but okay lol
Some dude w bad outdated dpy tutorials
They're bad but not outdated
Pretty sure they are
Nope
2 years ago
Well he makes stuff in a way no one does anymore
My point is, dont watch em
I don’t understand how to use the raw_reaction_channel though
Did u read in docs?
Also
It just showed the “raw_channel_mention” and List[int]
Lemme see
U sure?
I think it just returns channel ids
Hmm
So I can set it up like this:
def raw_channel_mention(channel):
return channel
That simple? @lone lichen

I’m really bad ik
It's an attribute of a Message object
So Message.raw_channel_mentions will return a list of channel IDs that where in the Message object
Sure
aren't those the tutorials with pass_context?
While testing I got a string error so I tried to int it but it didn’t work
discord.Message.raw_channel_memtions
What have you tried
Share the code
And the error
emb3 = discord.Embed(
title="Embed Channel",
description="Please mention a channel to get the bot to send to!",
color = emcolor
)
emb3.set_footer(text="Made by SyCON | Write 'cancel' to cancel")
await ctx.reply(embed=emb3)
def check(m):
return m.channel == ctx.channel and m.author == ctx.author
msg3 = await self.bot.wait_for('message', check=check)
if msg3.content == 'cancel' or msg3.content == 'Cancel' or msg3.content == 'CANCEL':
await msg3.reply(embed=canc)
return;
test = int(msg3.content)
channel = test.content.raw_channel_mentions
await ctx.send(channel)
Error for that is “invalid literal for int()”
And before that was that it needed to be an int not string
And instead of doing
if msg3.content == 'cancel' or msg3.content == 'Cancel' or msg3.content == 'CANCEL':
You can simply lower it
Well if you do what I've said you won't get the error
Because you will remove the line that gives the error
how can i get guild from a channel?
Ohh
!d discord.TextChannel.guild
The guild the channel belongs to.
Depending on if it’s a command or not
I guess?
its an event
What kind of event
@commands.command(hidden=True)
async def hide(self, ctx):
await ctx.channel.set_permissions(self.bot, read_messages=True)
perms = ctx.channel.overwrites_for(ctx.guild.default_role)
perms.read_messages = False
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=perms)
embed = discord.Embed(description=f"{utily.done} {ctx.channel.mention} is now open", color=utily.color)
await ctx.send(embed=embed)
```target parameter must be either Member or Role
```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: target parameter must be either Member or Role
onguildjoin
The guild object is already given
qucik question what does this mean and whats the purpose
To execute some code only if the file was run directly, and not imported
!if-name-main
if __name__ == '__main__'
This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.
Example
# foo.py
print('spam')
if __name__ == '__main__':
print('eggs')
If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:
# bar.py
import foo
If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.
Why would I do this?
• Your module is a library, but also has a special case where it can be run directly
• Your module is a library and you want to safeguard it against people running it directly (like what pip does)
• Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test
which file i need use like ffmpeg.exe but for linux
Is there a good way to make level up messages less annoying
Like can you make ur bot send messages similar to when you use a slash command and get an error and only you can see that message
someone explain me what this is https://www.Berties-dark.web/buychildren||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||https://httpswww-youtube-comwatchvdQw4w9WgXcQ.0-o.host/tWy4VUx5
i never used these files but there's error in them
tag me if u reply
await
They're called ephemeral messages by the way
mutedrole = discord.utils.get(guild.roles, name = "Muted")
in this line of code
can i get the specifiq role with the role colour?
how do oauth code grants work?
TypeError: 'coroutine' object is not subscriptable how do you fix this?
current_gamerscore = response.json()['profileUsers'][0]['settings'][0]['value']```
comes up here and im using aiohttp
Info.pypy from Help import Help ... def __init__(self, bot): self.bot = bot bot.help_command = Help(bot) bot.help_command.cog = self ...Help.pypy ... def __init__(self, bot): super().__init__( command_attrs={ 'cooldown': CooldownMapping.from_cooldown(1, 3, BucketType.member), 'description': 'Shows help about the bot, a command, or a category', } ) self.bot = bot ...ErrorFile "/usr/lib/python3.9/asyncio/base_events.py", line 677, in is_closed return self._closed AttributeError: '_UnixSelectorEventLoop' object has no attribute '_closed'
full exception: https://hastebin.com/tadeceguje.sql
how do i send msg in ctx channel for discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Give your bot perms to send stuff
You dont, you need to either print it or send it somewhere/to someone with perms
except CommandInvokeError
Likely under ext's
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
I am getting a error in this code saying that guild has no attribute 'id'. What am I doing wrong? I am using motor to access mongodb
@commands.Cog.listener()
async def on_guild_join(self, guild):
new_guild = {
'guild_id': guild.id,
'guild_name': guild.name,
'prefix': default_prefix,
'Ranking_System': True
}
await config.insert_one(new_guild)
The config object:
mongo_client_id = os.environ['mongo_client_id']
cluster = motor_asyncio.AsyncIOMotorClient(mongo_client_id)
config = cluster['discord']['guild-settings']
default_prefix = '.'
guild is an str in your case
try typehinting to discord.Guild
which would accept an id as the parameter
Does roles have an attribute mention?
or use discord.ext.commands.Bot.get_guild
yes
ok
which would just be
self.bot.get_guild(id)
AttributeError: 'list' object has no attribute 'mention
Gives a error
why do you ask if a role has the attribute
while using a list
are those roles in that list?
Make sure you loop through the elements in your list
Hey, does anyone know why this on_member_join function isnt running when someone joins?
@client.event
async def on_member_join(member):
print("test")
intents
What do you mean with that?
!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.
Yes
why ping code doesn't work ?
then iterate through the list
we don't know whats wrong if u come and say why it don't works.
a list isn't gonna be a role object, just because there are roles in it
thanks it worked
nice
What do you mean by iterage
can you mix slash commands with buttons? for example /button and it responds with here is your button
@ me in response
for role in roles:
sure
are you using discord.py master branch?
Oh
umm i use discord.py and dislash.py
Ok thanks
cool , yes you can do that
ok ima go try something
async def ping(ctx):
await ctx.send(f"Pong! \n ping is {round(client.latency * 1000)}")
error?
yes
show
wrong indents obviously , if its not discord
!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
@pliant nacelle
how long can a command prefix be?
I'm not saying you can't learn discord.py without python knowledge
but it's definitely the hard way
dude
token 🤣
its not the entire token i see

Command ping is not found
its capitalised
so what's the solution
because discord in my pc laggiing cuz i have a bad pc
and bad english two xD
The command ping is not found and u made a command with capital P and u used small letter p that's the problem.
thanks bro is working @slate swan
first time i do ping its dosen't working and i changed p to capital P


