class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC...
#discord-bots
1 messages Β· Page 751 of 1
GuildChannel is the type of channel which is in interaction.channel
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
Yea this exists
'ClientUser' object has no attribute '_roles' ClientUser = bot, _roles = roles
Bro, try doing interaction.guild.me
property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
bruh?
there is no
interaction.guild.permissions_for
!d discord.abc.GuildChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
property permissions: discord.permissions.Permissions```
Returns the roleβs permissions.
!d discord.Member.permissions
Nah.
No documentation found for the requested symbol.
is Music imported in __init__.py
None will spoonfeed
on_message:
level + 1
yeah
but use the async bridge
aiosqlite
yes
its the same as the old one
AttributeError: 'ClientUser' object has no attribute '_roles'
it's guild.me.roles
@nextcord.slash_command(name = "kick",description="kick a member",guild_ids=[ServerID])
async def kick(self,interaction:nextcord.Interaction,member:nextcord.Member=None,*,reason:str = SlashOption(default = "no reason provided",required = False)):
await interaction.response.defer()
if interaction.channel.permissions_for(interaction.user).kick_members is True and interaction.channel.permissions_for(self.client.user).kick_members is True:
if member is None:
return
await member.kick(reason=reason)
embed = nextcord.Embed(description=f"{interaction.user.mention} kicked {member}")
await interaction.followup.send(embed = embed)```
@slate swan Learn python
not plagarism
if we dont help you its because you copied
I told him the potential solution, but, uhhh
Typo
Because a user does not have perms , but a member does , and Guild.me returns the bot's member object for the Guild object
/roles
interaction.user is a member
no
!d discord.Interaction.user
The user or member that sent the interaction.
It can be both
Yep
And I'm not asking you to use that for inter.user , you have self.client.user there , that's what I'm talking about
instead of what?
interaction.guild.me.permissions_for(member)
^^ yes or no
No
then what?
if interaction.channel.permissions_for(self.client.user).mute_members is True:```
```roles = obj._roles
AttributeError: 'ClientUser' object has no attribute '_roles'```
use guild.me for it
how?
property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
if interaction.guild.me.permissions_for(member)
replace the self.client.user with guild.me
atleast someone says it
yeah
But why do you use an if when you could use bot_has_permissions?
BECAUSE SLASH COMMANDS DONT HAVE THAT
Wait what module are you using? Lol
nextcord
Bruh just use disnake, checks works for slash commands too
Lol
nextcord is official
tbh is a fork
Bruh disnake is a fork too, it has literally the same thing that has nextcord but slash commands are better
But official is better
It isn't official π π
nextcord is
What does "official" mean to you?
discord.py was official, then they stopped mantain it and people started use forks, there are planty of them and nextcord isn't official
then its the best fork
No it isn't π π
There isn't a best fork, they're all the same for the most of things, in disnake you can use slash commands with check both custom and built-in from the fork, disnake started used slash commands a lot before then nextcord and they're not in test phase anymore, they works fine
nextcord is bigger ( little racist but ) and bigger is better
Bro literally, what part of "they're all the same" you didn't understand?
there's no "bigger" fork existing , but if you're talking about features
Disnake is surely ahead others
TypeError: Timeout must be a `datetime.datetime` or `datetime.timedelta`not _MissingSentinel```
@nextcord.slash_command(name = "nickname",description="kick a member",guild_ids=[ServerID])
async def nickname(self,interaction:nextcord.Interaction,member:nextcord.Member = None,*,nickname:str = SlashOption(default = None,required = False)):
await interaction.response.defer()
if interaction.channel.permissions_for(interaction.user).manage_nicknames is True and interaction.channel.permissions_for(interaction.guild.me).manage_nicknames is True:
await member.edit(nick=nickname)
await interaction.followup.send(f"{member} nickname has been changed to {member if nickname is None else nickname}")```
no
nick (Optional[str]) β The memberβs new nickname. Use None to remove the nickname.
.... The error comes from somewhere you have Timeout
File "c:\Users\Kinder\Visual Code\PY Bot Moderation\cogs\moderation_slash_command.py", line 116, in nickname
await member.edit(nick=nickname)
File "C:\Users\Kinder\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\member.py", line 795, in edit
raise TypeError(
TypeError: Timeout must be a `datetime.datetime` or `datetime.timedelta`not _MissingSentinel
Ignoring exception in on_interaction```
Oh this , someone else faced this but was unable to solve , did you try asking this in their support server?
I think that's a bug? You're not passing any kind of timeout attribute
I got banned from it
hm , I'll ask and let you know
I pulled a uno reverse card
@twin moon try this member.edit(nick=nickname , timeout= member.timeout)
How can I host bot
nextcord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
like and then just get spoonfead?
your bot misses permission to edit nickname of that member
get a vps , or a host
But I have
Raspberry Pi and self host are always an option
Does it take money
why?
There are free as well as paid hosts
I don't know how to do that
You are the owner of the server right?
yes
How do you expect someone to edit you name
no one can touch the Owner
huh
Should work
Error
It can't run ?
yea but how?
Do u have intents? @green bluff
Invite an alt account and test on it
You are the server owner and the bot cannot ban, kick, mute, timeout or edit your nickname
The bot can edit roles tho
For the owner
Remove/add his roles?
Yea
Oh
As long as the role is lower than the bot's highest role
I see
is there a way to get a list of user_ids in a certain voice_channel they joined in
!d discord.VoiceChannel.members
property members: List[Member]```
Returns all members that are currently inside this voice channel.
ok ok thank you
hey if I wanted to make a modmail bot, what do you think is the best way to log conversations?
an on_message event
no like log the messages and save them for staff to see later
yeah
on_message and save the messages in a txt file for example
but u need to implement some checks to not interfere with other dms/channels/servers
@commands.command(description='')
@commands.cooldown(1,z, commands.BucketType.user)
async def spin(self, ctx):
fs = rnga()
so I want same value as fs in cooldown,any way it is possible?
how what
is there any free way to run my bot 24/7?
vps
is that free?
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.
Scaleway
Three distinct solutions to address your cloud infrastructure needs, your dedicated server solutions & hardware hosting
Linode
Our mission is to accelerate innovation by making cloud computing simple, affordable, and accessible to all.
Helping millions of developers easily build, test, manage, and scale applications of any size β faster than ever before.
from discord.py server^^
thankss
u can do that, first u need to check if the messages are in dms then u respond depending on how u wanna implement command listening for dms
in probot's case, in dms, it doesnt need prefix for commands
dms as in direct messages
what do younot understans
dms = your messages with someone
lol what
Hi.
how many buttons can you put on a single message
25 i think
alr
.
!d discord.ext.commands.dynamic_cooldown @leaden hollow
@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
Is there an alternative to guild.me.guild_permissions.send_messages for a specific channel?
make a function to convert it
hm?
Im trying to get attachments from a message object, but it returns this error, and its vague to me.
InvalidDocument: cannot encode object```
code:
```py
image = await self.bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
link = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',image.content)
if not link:
raw_link = image.attachments[0].url
else:
raw_link = image.content```
what's the message_check variable
/function
which app can i use to host bots
checks whether the message send is from a specific channel
but thats not the issue
What's the best way to fetch the full error traceback into string in on_command_error
you can make it send the error it self
EX:
async def on_command_error(context, error):
if isinstance(error, MissingRequiredArgument):
await context.send(error)
@staticmethod
async def error_embed(error) -> Embed:
eEmbed = Embed(title=f"{error}", color=0xFF0000)
return eEmbed
@classmethod
async def _on_command_error(cls, context, error) -> error_embed:
if isinstance(error, commands.MissingRequiredArgument):
eEmbed = await cls.error_embed(
error
)
await context.send(embed=eEmbed)
In my case, I use an embed that actually shows the traceback/error in the same way
@slim ibex I asked about traceback with a reason
guys
im planning to make a card game
every turn the bot will wait for message from 2 player
if 2 player finish chosing their cards, then next turn will continue
i know there is a way to wait for a message but idk how to make it continue only if both 2 player sent a message (and there will be a timeout also)
Wait for one then wait for another?
no it wont work
At the same time?
You will have to wait_for twice anyway
if just 1 person choose and the other don't it wont continue until both chose
If you are waiting for message
but how π
Just call it twice and get 2 results lol?
? wdym
no it wont work cuz if player 2 sent message it wont wait for it
uhm the invite?
ok wait
player1: discord.User
player2: discord.User
#just typedef don't mind
await ctx.send(f'{player1.mention} choose your card')
m1 = await bot.wait_for('on_message', check=lambda m: m.author.id == player1.id)
await ctx.send(f'{player2.mention} choose your card')
m2 = await bot.wait_for('on_message', check=lambda m: m.author.id == player2.id)```
@rapid walrus isn't this what you need
no i have tried but wont work
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.
cuz it will wait for m1 first until m1 is sent, but not m2, if m2 send first, it won't do anything
So you want it to be on the same time
Then make the check be like
lambda m: m.author.id in (player1.id, player2.id)```
And handle it properly
You didn't add py at the start that's why
ohH
That's for the first
i will try, thank you
For the second you gotta wait for the one who didn't respond
yea
π
Almost no time but what the issue is
Sorry gtg DM me so I can help you later or wait for another person to come
My embeds are always so squashed, is there a command that sets my embed to maximum size?
not that I know of, no. discord embeds are automatically sized to fit content.
may you show an example of what "squashed" means?
what do we do
Hey can anyone help me
I created a bot in discord.py
How do I read messages after the command is intieated(inside a COG)
Like if I put the command &cog and the question comes I want to give 30 secs to answer
How do I read the messages
ok π
Can anybody else help me
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Thanks I will try this
How do i delete channel overrides for user that are independently added to the overrides?
You can edit the override for user as None
How do I check if a message exists in a channel?
Wdym
I want to check if a message was deleted or still exists.
Iirc you can fetch the message
I solved the problem... Thank you
man what next π
!d import
7.11. The import statement
import_stmt ::= "import" module ["as" identifier] ("," module ["as" identifier])*
| "from" relative_module "import" identifier ["as" identifier]
("," identifier ["as" identifier])*
| "from" relative_module "import" "(" identifier ["as" identifier]
("," identifier ["as" identifier])* [","] ")"
| "from" relative_module "import" "*"
module ::= (identifier ".")* identifier
relative_module ::= "."* module | "."+
```...
Similar names: 2to3fixer.import
how do i import this new discord in python?
you r vietnamese
you already known
can i dms for help
ok
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Similar names: discordpy.discord, nextcord.discord
i cant dms u :>
add me
Nope
it's no longer.maintained
Not like it won't work
hey
how to run a bot and a flask file together?
sarthak
can u help me?
why would you want to do that, exactly?
to get the guild data
on my flask website
import discord
from discord.ext import commands, ipc
from flask import Flask, render_template, request, session, redirect, url_for
from discord.ext import ipc
import subprocess
import time
class MyBot(commands.Bot):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.ipc = ipc.Server(self,secret_key = "a")
async def on_ready(self):
"""Called upon the READY event"""
print(f"Connected as {my_bot.user}")
async def on_ipc_ready(self):
"""Called upon the IPC Server being ready"""
print("Ipc server is ready.")
async def on_ipc_error(self, endpoint, error):
"""Called upon an error being raised within an IPC route"""
print(endpoint, "raised", error)
intents = discord.Intents().default()
my_bot = MyBot(command_prefix="!", intents=intents)
@my_bot.ipc.route()
async def get_guild_count(data):
return len(my_bot.guilds) # get the guild object using parsed guild_id
my_bot.ipc.start()```
from flask import Flask, render_template, request, session, redirect, url_for
from discord.ext import ipc
import os
from subprocess import *
import time
app = Flask(__name__)
ipc_client = ipc.Client(secret_key="a")
@app.route("/")
def home():
guild_count = ipc_client.request("get_guild_count")
return render_template("index.html", content=guild_count)
if __name__ == "__main__":
app.run() ```
hey, how can i make changing statusses??? i.e. it will be changed every 5 seconds... etc.
ratelimits:
^
where are docs?
Do you know what a ratelimit is?
ratelimits are left ambiguous so people dont go push the limits
nope
they also scale, therefore apply separately to each person
called dynamic ratelimiting
It's different to a cool down
ah alr i'm googling
Discord Developer Portal
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
@devout iris
ah tysm
Can somebody send the discord page on the developer privacy policy?
idk anything about coding but i want to make a bot that records every message in a specified channel and instantly deletes it since i cant find one that exists already; can anybody help me scripting that?
??
If you know nothing about coding making a discord bot is not a good idea
It's far from a beginner project
!e
example- client.command() async def store(ctx): await ctx.send('no channel found')
something like that
idk exactly cuz i am new too
webhook for me = β ..... lol sorry i can't help... btw good luck
How to give role to user by server id and user id?
I just got a quick question, if you are not supposed to use discord.py bcz its dead then what are u supposed to use?
I don't think so
U can send a max of 120 requests every min, so about two requests in a second before getting ratelimited... I don't really think he is gonna get rateimited, provided, he isn't doing much ws intensive work
Well u can use dpy but a lot of people use disnake
if I change my current bot to disnake do I have to change all the code also? or will it still work?
replace every discord with disnake and it should work
okay, thanks!
how to connect and disconnect to voice channels?
disnake has shims for discord
so you don't really need to replace anything
it should work OOTB
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
!d discord.VoiceClient.disconnect
await disconnect(*, force=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Disconnects this voice client from voice.
@devout iris ^^^
How to check if the user has permissions to view a channel?
use has_channel_permissions check with read_messages=True
oh , a user
Yup
!d discord.TextChannel.permissions_for you can get perms on user using this
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
Tysm
using @bot.command() async def move(ctx): await ctx.send('hui') should create a command and with the prefix bot = commands.Bot(command_prefix='$') $ i should be able to run it like $move, right?
bc for some reason it isnt working
nvm im wrong
No
The bot won't know in which guild u want the perms from
How do I use an older version of dpy?
Why would u want to do that
Because I want to experiment with older versions
specify it in the command
how?
and now whenever I run my python file, it will use this version of dpy?
Ye
My bot just goes offline after like a minute after launching it could someone please look at my code?
Fixed it by using await asyncio.sleep() function
- you haven't even stated your problem
- you can perfectly do
admin_role = guild.get_role(id)
guys im trying to make a leader board for my economy but when i use the command i get this :
@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
users = await get_bank_data()
leader_board = {}
total = []
for user in users:
name = int(user)
total_amount = users[user]["wallet"] + users[user]["bank"]
leader_board[total_amount] = name
total.append(total_amount)
total = sorted(total,reverse=True)
em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = random.randrange(0, 0xffffff))
index = 1
for amt in total:
id_ = leader_board[amt]
member = client.get_user(id_)
name = member.name
em.add_field(name = f"{index}. {name}" , value = f"{amt}", inline = False)
if index == x:
break
else:
index += 1
em.set_footer(icon_url = ctx.author.avatar_url,text =f"Requested By {ctx.author}")
await ctx.send(embed = em)
how can i fix this ?
okay my self.config.test_accounts is a list of user ID's, is this correct for checking if the member.id is in that list? (This fires on member joins and removes
i don't think != is what I want bc that's not equal to but i just kind seem to remember what it should be
member = client.get_user(id_)
your member is None, check your id_
if member.id in self.config.test_accounts:
so since I want to see if the ID is not in the list i'd use if member.id not in self.config.test_accounts:?
smart
so I'm making a command which generates a random number x
then the commands waits for x seconds and sends the reply
I need to add a timeout for that x seconds so commands can't be stacked by the same user,no idea how to implement that
you're looking for a cooldown
it's a decorator
Is there anything we can distinguish whether the person joining the server is a bot or a user?
I know how to work with cooldowns decorator
if member.bot
Ah thx :)
well, you can set the buckettype to a user
yes
how do i make certain commands make it available to users who only have certain permissions?
I know that,the issue is I can't figure how to have the same "random" number as a bot messages as well as a cooldown
and that is with what library?
dpy
ok, I switched some names up, my bad
you need max_concurrency
check out the link above line 47
how can i make a command that shows me all the members in a sertain role?
do you pass the role as a mention to the command?
????
?giverolemembers @roleshit
they give the role name
the argument can be simply typehinted to a role
then you can do role.members to get all the members of that role
async def give_role_members(ctx, role: discord.Role):
so it's kinda a complex issue,i don't exactly know how to explain it
role = discord.utils.get(member.guild.roles, name=roleName)
role2 = role.members```
like this?
if you typehint the argument in the command, it'll automatically convert to that role
ok nice...
but is it correct
you just want to only run that command once per user in parallel...
I get it
I want the cooldown to be a "random number" which will be generated(most probably) when the command is run
that's the main thing
well, you can just add a sleep at the end, that'll just make sure the command isn't running twice by the same user while the previous one isn't done yet
commands.group(description='',invoke_without_command=True)
@commands.cooldown(1,z, commands.BucketType.user)
async def test(self, ctx):
z = rand()
await ctx.send(whatever)
await asyncio.sleep(z)
await ctx.send(f"Stopped at {z}sec")```
this is my current code
I said max_concurrency
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'member' is not defined
i get that error
that's a very english error
but idk how to fix...
you can just do ctx.guild...
no need for the member
unless it's in an event, then you don't have ctx
So simple yet so confusing..
checkEmbed = discord.Embed(description="**Searching** for username...", color=green)
checkEmbed.set_footer(text=f"Command executed by β’ {author.name}")
checkMsg = await ctx.send(embed=checkEmbed)
```Error I'm getting is:
ret = await coro(*args, **kwargs)
15.01 13:52:05 [Bot] File "/bot.py", line 1330, in discord
15.01 13:52:05 [Bot] checkEmbed = discord.Embed(description="Searching for username...", color=green)
15.01 13:52:05 [Bot] AttributeError: 'Command' object has no attribute 'Embed'
check your imports
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'member' is not defined
role = discord.utils.get(member.guild.role.members, name=roleName)
is this in a command or an event?
command
I've got bothimport discord and from discord.ext import commands, tasks
as mentioned earlier, just do ctx.guild
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'role'
i get this error when i do that
check the line where the error gets thrown, or just debug for a sec
will you start listening to what I say?
.
π¦ i am trying too
what r u trying to do
Can I just finish this, 1 moment.
Are you using this in an event, command what?
he doesn't understand the concept of typehinting which will convert the argument to a role object...
instead of "manually converting" it
command
fixed the code,it's working,Thanks
And you want to display all the members who have a specific role yes?
i do. its just that i just emojis instead of pinging roles, so i convert the emoji to a rolename
so let's say π is equal to roleA or what?
ok... lets just forget the emoji part, and imagine that they do
!members staff or something like that
yup, and staff is the name of your role
command would look like
async def members(ctx, role: discord.Role):
Hi, how do i start programming bots? I was thinking I want to do smth with apis
it wouldnt be that
So I have this colour of deepskyblue 00bfff but my embeds don't seem to like the code, anyone able to tell me why
then what
async def members(ctx, emoji=None):
it would be this
or
async def members(ctx, name=None:
0x00bfff
i made my bot so it replies to messages with a certain word in em, how do i make the bot react to the message with the provided word? message.react?
0x00bfff
there are libraries which simply are API wrappers to make it easier for devs...
role: discord.Roles makes it easier to handle
but I didnt do this before so I want to know where to start
the role arg can be name or id in this case
nice... but i dont want it like that
in the documentary of these python libraries
they contain examples etc
@slender pumice and @limpid thicket thanks for the help π
np
@frank tartan what r u trying to do
i just joined the chat so can u explain it to me
make a members command. so you can do
!members staff
and the bot will respond with everyone that has the staff role
[member.name for member in role.members]
then why dont u wanna use role: discord.Role
i dont want to explain again
discord.Role can be passed as a mention, id, or name so use the method which the users in the chat are providing (discord.Role parameter in command)
what do you think is the best way to make a modmail bot? Like through a DM channel, a thread, or through a channel
prob dm
You asked for the name, so it should work.
im confused
If you pass a role or set a default one you should use this.
still confused
Do recommend some kind of line paginator like the Python bot
How to get full error traceback into the string in on_command_error (and notice I am not asking to explain me the error handler or how to raise an error, alr know that)
var = error
but like what do i do with this???
then whats the problem with
async def members(ctx, role: discord.Role):
embed = discord.Embed(title="title", description = "description")
for member in role.members:
#do stuff maybe add them to a list or add them as an embed field
await ctx.send(embed=embed)```
Ok
End of conversation lol?
@client.command()
async def hasrole(ctx, role: discord.Role = None):
if role is None:
await ctx.send("Please specify a role.")
else:
if len(role.members) < 1:
await ctx.send("There are no members with this role.")
else:
memberslist = ""
for member in role.members:
memberslist += f"- {member.name}#{member.discriminator}\n"
await ctx.send(f"Members with this role:\n\n{memberslist}")
@hasrole.error()
async def hasrole_error(ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.RoleNotFound):
await ctx.send("Role not found.")
It has no command decorator.
lol i was suggesting code
If I want my bot to mention a category do I need to call get_category or get_channel?
how do i make a bot react to a message?
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
message.add_reaction()
@cloud dawn got these
.mention
Parameter is the emoji.
Seems like __traceback__ is empty
What about printing, error._traceback_
Already did look at code
It is None
oh yeah ik i'd need to .mention to mention it but first I need it to be a category object (I think that's the right term)
would this work?
There must be a way to get it
Yeah but you could also just use the ID with [#discord-bots](/guild/267624335836053506/channel/343944376055103488/)
Discord will format that into a mention
It is most likely fetched with external library
true, but don't mentions like that visually break somtimes?
No unless you put them in an embed.
What about this hacky trick
well it will be in a embed, but I'll do this for now. if I find a different way i'll try it then
try:
raise error
except Exception as e:
await ctx.send(e)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'member' referenced before assignment
I need the full traceback
There's no point in this "trick", it is just raising an exception and catching itself lol
ok i made my bot react with normal emojis, how do i use custom emojis?
Dropdown menus don't have default timeout right
You may bot.get_emoji by id
Then idk i don't get errors in my bot only when debugging.
I actually just need it to send the traceback to a private channel, but I need traceback and not the handler, people suggested me the handlers today lmao
Well it's better to handle them rather than just sending a traceback. I use the logging module if something serious goes down.
I just have a log and if it isn't serious i got my console.
so i do?
laugh_emoji = bot.get_emoji(id)
I have the handler for users and it works fine, but I am too lazy to connect to the VPS
That only takes like 2 seconds lmao
I have the commands for bot to automatically update without me needing to connect to the server and execute commands, so I want to send it tracebacks to the private channels so I don't have to open VPS at all 
On fatal crashes it wouldn't even send you the traceback
We never get fatal crashes (doesn't mean we can't but the chance is really low)
But never 0 π
Btw about chances
I made a function for like "chances selection", but it is sometimes smoking grass and returning None, I wonder what have I missed in it
does anyone know how can I make embed message with this reactions?
my bot doesnt work anymore it says i made too many api requests
how do i prevent this from happening again
Forgor
!e
from typing import Any
from random import randint
def choice(objects: dict) -> Any:
range_dict = {}
current_point = 0
last_number = 0
last_item = list(objects.keys())[-1]
for item in objects:
next_point = current_point
if last_item != item:
next_point += int(objects[item] * 10)
else:
last_number = next_point = next_point + int(objects[item] * 10) + 1
range_dict[range(current_point, next_point)] = item
current_point = next_point
num = randint(0, last_number)
for i in range_dict:
if num in i:
return range_dict[i]
for _ in range(5):
print(choice({'bruh': 70, 'no': 30}))```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
001 | bruh
002 | bruh
003 | no
004 | bruh
005 | no
You probably have the while loop somewhere
Somewhere in a bad place*
where can i share big amounts of code for discord py
These are buttons with emojis set
welp
You can use pastebin, use collaboration session for VSC, post it to gihub and open access to certain people there are many ways
@vale wing
freecodecamp-
There's a decorator
what does that mean
!d discord.ext.commands.Bot.command simpliest implementation
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
and use discord.ext.commands.Bot instead of discord.Client
@bot.command()
async def somenicecommand(ctx):
await ctx.send(f'Hi')```
ohh i understand why i got api blocked
its cause the event is looking like every second for commands thats why?
Nope
The event is something about websockets and gateway, dunno about that very much
But actually discord sends the events to you
what guide/tutorial should I use for learning then?
i dont know what guides are good or bad sorry
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Very good even after maintenance end
@client.collect(rin.Event.GUILD_MEMBER_JOIN, amount=10)
async def foo(members: list[rin.Member]) -> None:
if all([member.created_at < GUILD_MIN for member in members]):
# remove all members for anti raid
``` Thoughts on this feature (collection) I plan on adding to my DAPI wrapper?
@client.command(name = 'event', help = 'shows all active events NOT WORKING')
async def event(ctx):
for event in ctx.guild.scheduled_events():
print(event.name)
i having exterme probelms with getting a list of events
** this is the error ive gotten**
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'list' object is not callable
I suggest using typing List instead of a list object.
And why is that exactly
Because i think it looks better, and typing does a better job documenting it.
How do I write on it?```py
blacklist[str("profile")]["blacklisted"] = "true"
with open(f"./data/users/{member.id}.json", "r") as f:
user = json.load(f)
blacklist[str("profile")]["blacklisted"] = "true"
with open(f"./data/users/{member.id}.json", "w") as f:
json.dump(blacklist, f, indent=4)
I've import annotations from __future__ so all annotations are strings either way. And in future version of python it will be like list[] dict[] etc
All the type checkers so far are supporting this as well, no brainer
hello guys. My problem is this. the fact use dadjoke id
lib: discord_components
code:
@commands.command(aliases=["Facts","facts","Fact"])
async def fact(self, ctx):
await ctx.send(embed=discord.Embed(color = 0x990033, title="Did you know? :astonished:", description=f"{random.choice(facts)}"), components=[[
Button(style=ButtonStyle.green, label="Next", custom_id="button2"),
Button(style=ButtonStyle.red, label="Stop", custom_id="button3"),
]])
@commands.Cog.listener()
async def on_button_click(self, interaction):
if interaction.component.custom_id == "button2":
await interaction.respond(type=7, embed=discord.Embed(color = 0x990033, title="Did you know? :astonished:", description=f"{random.choice(facts)}"))
elif interaction.component.custom_id == "button3":
await interaction.edit_origin(embed=discord.Embed(color = 0x990033, title="random Facts Stopped!", description=f"If you would like to use it longer, then push the next button or >fact"))
@commands.command()
async def dadjoke(self, ctx):
await ctx.send(embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"), components=[[
Button(style=ButtonStyle.green, label="Next :arrow_forward:", custom_id="button"),
Button(style=ButtonStyle.red, label="Stop :octagonal_sign:", custom_id="button1"),
]])
@commands.Cog.listener()
async def on_button_click(self, interaction):
if interaction.component.custom_id == "button":
await interaction.respond(type=7, embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"))
elif interaction.component.custom_id == "button1":
await interaction.edit_origin(embed=discord.Embed(color = 0x34568B, title="Dad Jokes Stopped! :police_officer:", description=f"If you would like to use it longer, then push the next button or >dadjoke"))
woah
Ahh okay, well other than that it looks fine afaik.
!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.
Alright sounds, good def something I will be adding
If you didn't know as well I'm rewriting Lefi so now it's a whole different code base
π
I'm still writing my slash bot :3
Hm..
Thinking about things to add, i'm currently making a nice wrapper for postgre
whats wrong with u ?
Can someone help with it? ^^
Nice, I'm gonna remove vanilla chat commands and keep the wrapper purest in form
ur trying to create a blacklist system correct
I'm hoping this time my bot can survive a bit longer. I was kinda annoyed by the fact discord.py stopped and the whole message intents things. Now trying to make the bot without any intents (as much as possible).
so, anybody? 
{
"profile": {
"moderator": "false",
"blacklisted": "false"
}
}
syntax it correctly and show only the problem not the whole code
so what are u attempting to do
thats where im confused
set false to true -.-
ohhhhh
Most of use don't really like helping with json as a database.
I don't want to use a database
9/10 reasons is because people don't want to learn it. SQL makes your life so much easier.
ah
promt_1 = promts["1"].replace("__USER__", f"<@{ctx.message.author.id}>")
@blissful bone found the problem
this is what i used for my ticket bot
user = json...
blacklist i tried to get -.-
lol it happens dont worry
ctx.message.author.mention is a thing.
promt_1 = promts["1"].replace("__USER__", ctx.author.mention)
``` same code
i was giving an example
for replace
Anyone know how to install the pillow package? I tried the thing from https://pillow.readthedocs.io/en/latest/installation.html but i just get failed to install
!pypi pillow
@client.command(name = 'event', help = 'shows all active events NOT WORKING')
async def event(ctx):
for event in ctx.guild.scheduled_events():
print(event.name)```
i having exterme probelms with getting a list of events
this is the error ive gotten
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'list' object is not callabl
pip install Pillow
That's where i was then i went to installation but i just get failed to install
Hey uhm , how do I give a user a role?
So far i got this: py guild = ctx.guild role = discord.utils.get(guild.roles, name=d2ndQuestion) member = str(applicationID) await member.add_roles(role, reason="Application accepted")
tb?
applicationID is a user btw
This one works
Nvm doesn't work. It installed but i still get no module "Image" on my import Image
Well it's Pillow not Image

from PIL import Image
Shit they switched it then?
Always has been this way.
how do i make the bot embed colour be random?
ive done it before but forgot how to.
Use to be import image...
there was a specific keyword i used which made it unnecessary to get a colour array
!d discord.Colour.random
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
ty
Hello,
I am doing a bot with discord.py and I am using a class Name(commands.Cog): ... and i would like to know how i can in this class create a new object from a "subclass" class Type(?) in which I can await to send new messages in the channel.
Example :
class Type(?):
def __init__(self, channel, smthg):
...
???
async def print(self):
await self.channel.send("Test")
class Name(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.obj = Type(channel, ?)
@commands.command()
async def test_print(self):
await self.obj.print()
how do i make my bot send a DM to the person i mention?
async def on_message(self, message):
for member in message.mentions:
await member.send('Hi')
this is not working
if it's "not working" there are 2 options
- your event never gets triggered
- you have an error handler which isn't showing the error
you don't have to subclass anything...
I need discord.py documentation commands π¦
its saying there is no attribute mentions in message
but stackoevrflow says there is
O_o
show me the full error traceback
the docs should be your source
ah alr
i know that i don't have to but i want to do that to have many subclass to create many type of object in this class
can you try to describe in 1 sentence what the goal of that class is?
there's not really a need for you to store this as a class... you can perfectly store it as a dict
with the key being the channel_id and the value whatever you like
my big class is Game and I want to create some subclass for different game and each subclass have the same methods name
yeah, there's not really a need for a class for each game, you can just store the progress in a db or whatever
for example obj.new, obj.turn, obj.win ...
yes but i want to have many instance of the same class fo example if there are 2 games ( match ? ) of the same type
well, make a subclass for every type of game, there aren't that many, right?
your "game" class doesn't need to be subclassed ofc, since it's your superclass
that should be an interface / abstract class
Hey, i want to make an error if a user hasn't enough permissions, but this doesn't work. I use cogs, but i think it should works anyway.
always handle the other errors too
else:
chances are, there's an error which you just "hide" because you don't handle it
Well, it's not error, ctx, but ctx, error.
oh now its working fine. thanks a lot!

How would I put in a date and time and I would get a timestamp back
!e
from datetime import datetime
date_str = "01/01/22 05:34:19"
date_obj = datetime.strptime(date_str, '%d/%m/%y %H:%M:%S')
print(date_obj.timestamp())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1641015259.0
Depending on how you have the date as string you will need to use some other things in the strptime method.
https://strftime.org
Here you can see what to use.
A quick reference for Python's strftime formatting directives.
And also compare to those I used.
Ty
yo guys
something really cool i added to my bot that u should try out
u know how if u have three of ` b4 and after ur message
it pulls up this thing
ya so i made my bot acc run any code that the user puts and sends any printer output to the channel
it makes for a rlly cool python scratchpad
what vscode theme is this it looks really cool
Is it open to the public?
wot is?
Yeah
The command you made
u want code?
No
!e
print("Your idea already exists")
@final iron :white_check_mark: Your eval job has completed with return code 0.
Your idea already exists
eh true but its just me and my friends
yeah, also
WHAT
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
Your friends can fuck with your system
HOW DARE THEY STEAL MY IDEA
I wouldn't suggest it
You most likely saw their idea and used it
theoretically, but their kinda incompetent so im not worried
no fr i thought i was the first one to do it
You're definitely not
man that sucks
That's not to say you can't try to make your own though
It's good learning experience
true
Also, you'll need to allocate permissions to the bot, so they dont f*** with it; like accidentally deleting files, data overflow, infinite loops, and prevent realtime response. (A while loop that prints every sec, for example).
!e - A quick example; checking read & write premissions -
import os
from os import W_OK as w
from os import R_OK as r
k = [w, r]
[print(f, i, os.access(f, i)) for i in k for f in os.listdir()]β
@rugged steeple :white_check_mark: Your eval job has completed with return code 0.
001 | Pipfile.lock 2 False
002 | Pipfile 2 False
003 | config 2 False
004 | snekbox 2 False
005 | user_base 2 False
006 | tests 2 False
007 | LICENSE 2 False
008 | Pipfile.lock 4 True
009 | Pipfile 4 True
010 | config 4 True
011 | snekbox 4 True
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tuqilufebe.txt?noredirect
whats the event for on a user dm?
on_message
to check if it's a user dm => message.guild is None
alr ty
USW6GT4
is making a reaction based or command based ticket system better?
Button based 
Jk that's up to you, although users like easier interface which is reactions and buttons
I use pycharm, there's called "Vuesion Theme"
thanks
I have a ticket system and this is the full file https://mystb.in/ChainContinuingTabs.python but then i got this error and when i went and pressed the reaction it didnt make a new channel anymore. Like whenever I deleted the txt file and did everything over again it worked fine but when I reran the bot again, it gave me the same error
Can someone help
error explains itself: you're trying to get a key from your ticket_configs which doesn't exist
It does
Itβs this file
it does not
2 options
A. you deleted it
B. you key is saved as a string and you pass an int or vice versa
why don't you use json for this?
Cuz I watched a tutorial on it
yt tutorials suck mostly if we're talking about these libraries
they're too concrete or implement bad methods which you can blindly copy paste thinking "if it works, I'm fine with it"
Concrete?
Like they only talk about what they need, chances are, you need something different which just messes the rest up
Greatest example is: they use json as a db
Oh
Or even worse in your example: a txt file
Yeah I realized that
json as a db π¬
that idea has been out there for years now
any code?
Guys, please tell me why you need it - GUILD MEMBERS INTENT
And - GUILD PRESENCES INTENT
And what is the difference between them?
You can think of intents as a sort of flag, the flag tells the gateway what to send to the client. In the case of having Member intents the guild will send data corresponding to Members, and in the case of Presence intents it will send back data corresponding to Presences. Without them you would not receive the data.
GUILD MEMBERS INTENT - it's: teg, avatar, name etc?
?? What
I wanted to ask that I can get the listed member information?
Its, everything
No member intent, no member data
No presence intent, no presence data
Not even any partial data
thanks you so much
how do i make my global error handler send errors in the server?
You would fetch the channel and then send the errors
You need to update python with pip install discord --upgrade pip discord right?
need help
So I've recently learnt that I should keep my database connection open all the time instead of opening and closing it each time
I understand that I need a function in my main file connecting to my database
I've added that but, now what?
by any chance does anyone know how to get your token hidden (replit)
(Continuing on this thread) How would I execute things in my database?
I have no idea what I'm doing in this department
put in key TOKEN
put in value your token
and then do py bot.run(os.getenv("TOKEN"))
ty
that will make your token isnt public on repl.it

why doesnt it send the reason for the error not sending in the channels?
class ErrorHandler(commands.Cog):
"""A cog for global error handling."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.CommandOnCooldown):
message = f"This command is on cooldown. Please try again after {round(error.retry_after, 1)} seconds."
elif isinstance(error, commands.MissingPermissions):
message = "You are missing the required permissions to run this command!"
elif isinstance(error, commands.UserInputError):
message = "Something about your input was wrong, please check your input and try again!"
else:
message = "Oh no! Something went wrong while running the command!"
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
def setup(bot: commands.Bot):
bot.add_cog(ErrorHandler(bot))```
Your setup function is indented too far
It shouldn't be indented
like that?
I can't see the indentation but probably
Should work
it only sends here
it gave me an error i even imported os
Whats the error?
Did you even read the error?
Print your token and visually compare it to what discord gives you
So I figured out how to keep my connection open
Would I still have to commit the data I wrote every single time?
Hello, I want my subcommand to be called async def discord(ctx, username = None):
Issue is, I can't reference any objects with discord in it now.
And discord.Embed now doesn't work, any work arounds?
just use the name kwarg at the @command() decorator
and change your function name to anything
Oh like you mean like alias?
Oh I see, thanks.
And name would take priority yes?
yes
yes
Thanks π
woohoo got collectors working π³
This defo doesn't work with events that return more than 1 parameter though, no clue how I'm gonna fix that as of right now
Mine
oh you are making your own api wrapper?
I've made one already, I'm making a rewrite of that one rn which is what I just showed
Thanks
Oh man this feels pretty convoluted
Gonna need to unpack but then it gets harder from there
If I want to get the value of a field in a embed I would do something like this right? where the [0] next to fields is the number of the field I am looking forpy message.embeds[0].fields[0].value
I don't think that's how dicts work
what are you even trying to do
Why do you need to get the data of an embed?
It's complicated and I'm too tired to explain it but basically I'm making a task event which checks channel A for any msgs containing specific words (Warn, Ban, Mute, Kick) and if it finds a msg with that in the msg embed title then it constructs a embed with the values of the first embed and sends this second embed to channel B.
@final iron @slim ibex @quaint epoch
And this is what I have so farpy @tasks.loop(minutes = 60) async def moderation_logs(self): key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] checked_logs = [] # A list of ID's of the messages the bot has checked, Probbabrbly should be written to my DB case_count = 0 # A incrementing number for the moderation case's, will be written to my DB moderation = self.bot.get_channel(id = 885569667861717042) # The channel it is sending the new msg to clifford_log = self.bot.get_channel(id = 500768218257031168) # The channel it is searching with moderation.channel.typing(): messages = await clifford_log.channel.history(limit = 10000)#.flatten() for message in messages[0:]: # Making the bot search through the messages chronologically (I think) if message.id not in checked_logs: if message.author.id == 776782769312628746: # Checking the message author is my other bot which is causing me to make this lenghty workaround if len(message.embeds) > 0: if key_words in message.embeds[0].title: # Checking in my keywords are in the retrived embed title, I want it to make a count of how many times it finds each word and I'm thinking a dict would be good but I'm not too sure how to go about that rn embed = discord.Embed(title = f"Case {case_number} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp) embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url) embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url}) embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True) embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True) if message.embeds[0].fields[3]: # The 4th field of the original embed doesn't always appear so i'm accounting for that embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value) embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value) checked_logs.append(message.id) # Writting the ID of the latest checked msg to a list so it knows not to check this again await moderation.send(embed = embed)
Maybe read the docs or convert the embed to a dict to test it, Idk
I'm not sure how to work with that
i'm like 60% sure it'll work, I just need to make sure I have all the logic sound and that I am pulling all of the values correctly, even if their not in the correct places i'll still count it as a win
Some cool stuff possible with collectors π
heh its true
My question is this when you get all of the items in a collection in mongodb using pymongo What kind of list will you get
import pymongo
client = pymongo.MongoClient('URL')
db = client.db
collection = db.collection
document = list(collection.find({})
The database is like this
{
"_id": {
"$oid": "ID"
},
"question": "question",
"answer": "answer"
}
Can anyone tell me how the list is going to be like
this is for a discord bot
NeverMind I already Got the answer
[{'_id': ObjectId('ID'), 'question': 'question', 'answer': 'answer'}]
Make sure your bot has permissions to add roles
also, ctx.send() should be awaited
can you send the full error traceback?
ye nah i figuired it out its just that the bots role was below the muted role
im just bad at coding lol
channels are guild binded....
Can anyone help me in #help-broccoli
Hey can anyone answer my simple question
I created an embed command that will make an embed like &embed Hello "This is it" FFFFFF
But when I tried to put in a nitro animated sticker it justs shows the text of the emoji
im trying to make a help command where i can use a input
File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
sticker , or emoji?
Where are you putting the emoji, in the title?
well no the description
titles can now show custom emojis iirc
like :arrow:
Does the bot share a server with the emoji?
yes
@bot.command()
async def help(ctx):
emb=discord.Embed(title = "Help commands", color = discord.Colour.random())
emb.add_field(name = "List of command types", value = "fun, moderation", inline = False)
await ctx.send(embed=emb)
if "fun" in message.content:
e=discord.Embed(title = "fun commands", description = "insert commands", color = discord.Colour.random())
await message.send(embed=e)
can someone show me what im supposed to do
emoji
like this one and more
Those are the only reasons it would break, unless your command modifies the text in some way, since embed descriptions should handle emojis from mutual servers fine
Use the escaped name of the emoji and make sure that the bot is in the server the emoji is from , escaped name can be get from using \:emoji\:
wdym what your supposed to do
also subclass HelpCommand, not remove it
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
I recently reorganised my code for my discord bot, and the cogs aren't in a child directory anymore but in a parent directory. I have tried things like:
for filename in os.listdir("./cogs/CogFolder"):
if filename.endswith(".py"):
client.load_extension(f'CogFolder.{filename[:-3]}')```
What am I doing wrong?
show your dir
you need to load them as cogs.CogFolder.{filename[::-3]}
Since you are looping inside that path
hello, how would i get my discord bot to read a status and give a role. for example, i put /myserver in my status and the bot will apply roles to the user
you'll need the on_member_update event for this
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
use this in on_member_update , check the activity.name , it will return an str form of the user's status
My wifi oof
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.security.automod' raised an error: AttributeError: module 'os' has no attribute 'os' ://
So your saying is that when someone types in the emoji then replace the :: with \: \:
Could you show the code
inside the code
for filename in os.listdir("./cogs/CogFolder"): if filename.endswith(".py"): client.load_extension(f'cogs.CogFolder.{filename[:-3]}')
That was just a markdown error from my side , try getting the long name of emoji by using \ before the emoji and copy paste that long text with id in your code for the emoji
Did you do os.os somewhere?
No :c
@quaint epoch You can have member.guild_permissions , or channel.permissions_for(member)
alr
show your imports
thanks lol
yw
from asyncio import events from distutils.log import error from http import client from multiprocessing.connection import Client from operator import truediv from pydoc import describe from sre_constants import CATEGORY_LINEBREAK from telnetlib import OUTMRK from textwrap import indent import discord from discord.ext import commands import os from tokens import TOKEN import json
@novel apex
I mean in the cog file you are trying to load , the file name automod where the error is coming from , also check there if os.os is there
!e import os
os.os
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: module 'os' has no attribute 'os'
This is what u did somewhere
Yes, import "os" into the file
hey, could someone help me with these errors? I got the same code from an older bot and it works fine there. I have the code for the bot shared up in different files also
File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Admin\PycharmProjects\The-KnightBot\commands.py", line 12, in <module>
async def setup1(ctx):
File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\core.py", line 1433, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\core.py", line 242, in __init__
raise TypeError("Aliases of a command must be a list or a tuple of strings.")
TypeError: Aliases of a command must be a list or a tuple of strings.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Admin/PycharmProjects/The-KnightBot/main.py", line 21, in <module>
import discord_events
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Admin\PycharmProjects\The-KnightBot\discord_events.py", line 2, in <module>
from main import *
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Admin\PycharmProjects\The-KnightBot\main.py", line 41, in <module>
bot.load_extension("commands") # use name of python file here
File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands' raised an error: TypeError: Aliases of a command must be a list or a tuple of strings.
Using cogs i can seperate commands into groups right?
yeah
And the os.os?
aliases = ["alias 1"] , not a single string
u are kidding me... I forgot the Square brackets on aliases, sorry it was a dumb mistake
its working now tho, ty
I don't know, but I don't think so
lol, sot pretty bad, sorry xd
You can just ctrl+f and search for os.os to check if it's there in most of the ides
I already searched and there is not
That's weird ,. Cause that is what the error says , show the imports in the cog
how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable
how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable
how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable
even when the bot restarts?
just create a botvariable which stores the data based on the user id
so when they kick or unban or ban it will be sent there
that's just an argument...
from asyncio import events
from dis import disco
from distutils.command.config import config
from genericpath import exists
from http import client
from importlib.resources import path
import json
from webbrowser import get
import discord
from discord.ext import commands, tasks
import re
import os
he aksed for a ctr+f of os.os, not a list of your imports
Ups, wrong reply
.
any chances you have a file named os? lol
no
how to make a commands logging system>
so
they sent a command like /kick
then once the user is kicked it will send the output in a channel that the server owner set the channel id to
You would create a database
With the channel id
Then just get the id, fetch the channel and send the message
With a little trickery you can make a cog specific check so whenever a command in the cog is used it will log it
how to create a database
Is this going to be available to every server the bot is in or just yours?
Yeah, you would need a database
I don't know anything about the pros and cons of the different db's but I use sqlite3 and its dead simple
can you help
With what?
cool
I can help with ideas on how to do it and errors you encounter but I'm not going to spoonfeed you code
yes
With which part specifically
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
A really nice interactive website to help you learn
Its dead simple and you'll most likely pick it up in 1-5 days
But no guarantees
do you know how to use mongodb?
Nope
wait i found that there is module for sqlite
yes
aiosqlite
!pypi aiosqlite
You would want to use this
!pypi asyncpg
:3
asyncpg is for Postgres
hjmm
Oh , can you send the complete traceback ( error message) you got
!paste it would be long so consider using this
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.
Yea, but u saying to pass in a user, which is wrong (as long as u ain't referring to Member as User)
pep8 hahaha
nope arguments can only be executed within the command (!test 1 2 3)
I am talking abt file atachment
Lika ataching the file and uploading it to specific directory
Just read the message's attachments
E.g Message.attachments
!d discord.Message.attachments
A list of attachments given to a message.
apparently this body form is invalid and idk why
Traceback (most recent call last):
File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.5.value: This field is required
@bot.command(aliases = ['whois', 'ui'])
async def userinfo(ctx, member : discord.Member = None):
if member == None:
member = ctx.author
roles = [role for role in member.roles][1:]
emb=discord.Embed(title = f'{member.name} user info', color = discord.Colour.random(), timestamp = ctx.message.created_at)
emb.set_thumbnail(url=member.avatar_url)
emb.set_footer(text=f'Requested by {ctx.author.name}')
emb.add_field(name="nickname", value=member.display_name, inline=False)
emb.add_field(name="Discord name", value=member.name, inline=False)
emb.add_field(name="ID", value=member.id, inline=False)
emb.add_field(name="account creation date", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)
emb.add_field(name="server join date", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)
emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]), inline = False)
emb.add_field(name="top role", value=member.top_role.mention, inline = False)
emb.add_field(name='Is bot?', value=member.bot, inline=False)
await ctx.send(embed=emb)
emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]), inline = False) are you sure roles contains something?
also, I'm not sure on the last line if value can be a boolean
wdym by if the role contains something
make sure the list is not empty
field 5 == ```
emb.add_field(name="server join date", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)
Joined at states
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
None == empty
aight, I just miscounted the field woops
i think im to stupid to understand what im supposed to do
anyways, you should add checks before adding certain fields I guess
ah
