#discord-bots
1 messages ยท Page 549 of 1
and you want to send "False" using a webhook?
wow i never knew this
Woagh
yes
???? i have an on message event which runs at the same time when you put in the command so how can i fix that??
or true
well personally i'd create a webhook > send the message > delete the webhook
i watched a video
where they are doing somtthing else
but the error is same and they fixed it
yes
depends
will watch that and thn help me
wdym by that
Ig
on bot =
@boreal ravine like the attributes dont work idk why
wdym by the attr's dont work?
the flags names for example = hypesquad_balance
whats the problem exactly?
for nitro it's premium_type right ?
rtd on that one
rtd ?
the docs
Or just replace .com with .dev
There are no flags for Nitro
You gotta check on your own
premium_type is the one
Doesn't exist :)
im just looking for others
it exists cuz i find nitro users with that 
Then show me the documentation where is shows it exists
As it doesn't exist
Those are the only flags
Discord doesn't have a bit shift for Nitro in the badges bitfield on their API
So you have to manually check by yourself
For example, if the profile picture is animated or if the user has a special discriminator or a banner, etc.
Source to the Rust file src/methods/users.rs.
i dont manually check tho..
Or make a manual api call, which is pepega if you have what you need
That's the game SDK though
Only thing you can do is a manual API call
/users/{user.id} and read the value in the premium_type field
well? it still shows the information, and even tells you if its classic nitro or not, anddd it's better than doing a raw api call
Whatever, maybe reading can help ๐คก
another way would be premium_since, returns None if the user doesn't have nitro iirc ๐
wasn't premium for boosters?
oh really?
yeah i just looked it up and it's for boosters
not sure if it's because of discord's api itself but there seems to be no way to check for nitro
well that's ๐๐
even https://discord.id/ doesn't return nitro boosters
How do I set 'all' and 'max' as the maximum value in the bank for my currency bot?
so i fixed the error of it returning none when setting the afk, but now it sets the afk, removes it, and sets it again. it works how it should when you send a message, but the setting part is messed up. any way to fix this?
My code:
@commands.command()
async def afk(self, ctx, *, message = "No Reason Specified"):
record = await afk_list(ctx.author.id)
if record:
embed = discord.Embed(title = 'AFK Running', description = f"{ctx.author.mention}, You Already have an afk running", colour = discord.Colour.red())
await ctx.send(embed = embed)
else:
try:
await add_afk(ctx.author.id, message)
await ctx.author.edit(nick = f'[AFK] {ctx.author.display_name}')
embed = discord.Embed(title = 'AFK', description = f'{ctx.author.mention} I Set Your AFK\n Reason: {message}', colour = discord.Colour.green())
await ctx.send(embed = embed)
return
except:
await add_afk(ctx.author.id, message)
embed = discord.Embed(title = 'AFK', description = f'{ctx.author.mention} I Set Your AFK\n Reason: {message}', colour = discord.Colour.green())
await ctx.send(embed = embed)
import discord
import googletrans
from discord.ext import commands
from googletrans import Translator
@commands.command(name = 'translate', help = 'Translates a series of text to any language you want')
async def translate(self, ctx, lang, *, args):
translator = Translator()
translation = translator.translate(args, dest=lang)
em = discord.Embed(
name = 'Translation',
description = f'{args} ---> {translation.text}'
)
await ctx.send(embed = em)
i keep getting an command error on this command.
wait nm this api is old lmao
how do i make my bot say smthn to like a specific channel?
like if i type a certain command, it sends a message to another channel
But how does he set "channel" to be a specific channel? ๐ค
You can't be doing my man bad like this
well, mans asked how to send it not how to set it ๐คทโโ๏ธ
still, i'd recommended reading the docs, many ways to get a channel
most basic one would be channel = bot.get_channel(id_goes_here)
ye, that was my question
or use a parameter and type hint it to be a channel
Then you can do !say #channel a message here
ok
how do i invoke a command from within a on_message event
Does anyone know how to use a discord widget on GitHub?
Ik this is not related to discord.py but
its the closest
you mean a webhook?
i dont understand
oh
just view the source code and copy it lol
yeh but i want my own server instead
Then change the source code?
k
ok
which product do I choose for a bot's host
@bot.command()
@commands.has_permissions(administrator=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedrole = discord.utils.get(guild.roles, name = "Muted")
if not mutedrole:
mutedrole = await guild.create_role(name = "Muted")
for channel in guild.channels:
await channel.set_permissions(mutedrole, speak=False,send_messages=False,read_message_history=True,read_messeges=False)
await member.add_roles(mutedrole, reason=reason)
await ctx.send(f"Muted {member.mention} for reason {reason}")
await member.send(f"You were Muted in the server {guild.name} for {reason}") ```
why this is not working
class UserInfo_Button(discord.ui.View):
@discord.ui.button(label="View Member's Roles", style=discord.ButtonStyle.blurple)
async def receive(self, button: discord.ui.Button, interaction: discord.Interaction):
member = discord.Interaction.user
for x in list(discord.Interaction.guild.roles)[::-1]:
memberRoles = f"\n{x.mention}"
embed = discord.Embed()
embed.add_field(name="Roles", value=memberRoles)
await discord.Interaction.response.send_message(embed=embed, ephemeral=True)
@commands.command()
async def hi(self, ctx, member: discord.Member):
member = ctx.author or member
embed = discord.Embed(
description=member
)
await ctx.reply(embed=embed, view=self.UserInfo_Button()
```i have this, but below i have a command which has an arg `member`, so how do i make the interaction get the `member`'s roles? im certain its not `discord.Interaction.user` since thats for the user who clicked the button
stop. copying. code. when.
member.roles
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
i know that but then its in an interaction
discord.Interaction.user.roles then? idk read the lib's docs about this
but thats for the user who clicked on the button, not the member arg
Who's "member" in this case then
the author?
member can either be the author or a @member (its an arg in a command)
i dont see a member arg anywhere
edited
hm
Hello there ๐
Is this any way to make a command both a regular one and slash command under the same function? I'm using discord_py_slash_command for the slashs
@commands.command(name="info")
@cog_ext.cog_slash(name="info", description="some description")
async def cool_func():
await ctx.send("some info")
Of course, this won't work, but is there any workaround?
\๐ฟ
I don't think so
just make one slash & one normal command ๐ง
๐
Alright then, I'll do that if there is no other solution to it
It's extra code though, but I guess it'll have to do
cloud i'm positive?
# checks if member has banner or not
if bool(member.banner) is True:
fetchedMember = await self.bot.fetch_user(member.id)
# new_embed.set_thumbnail(url=fetchedMember.banner.url)
else:
pass
```did i do something wrong here? i ran the command and mentioned someone with a banner but then its not showing in the embed thumbnail, theres nothing in the thumbnail
member.roles
i already said, in the interaction (button), not the command
there's some problems w avatar_url in 2.0, could be the same with banner_url
well good for you ๐
??
not extremely sure i understand? a member object is a member object regardless
break can be used only in loops, I think what you want is return.
Hi, so I've coded a discord bot using nodejs once a while back, I remember I did a command handler and a event handler where i have a index.js file, and two different folders called "commands" and "events", so inside the commands folder, each command the bot has is in their own file within that folder, and every event that's called is in their own file in the events folder, example:
index.js
commands โ
ping.js
info.js
help.js
kick.js
etc...
events โ
message.js
ready.js
How can I do this with python?
Code?
Example for using cogs in discord.py. Contribute to ScopesCodez/discordpy-cogs development by creating an account on GitHub.
Just return.
you don't really need separate files, but yeah, cogs are what you wanna look at
It's muuuch easier to have a command handler and event handlers of what I learned
Yes.
So cogs it is, ty guys
return stops the command ๐
np, good luck
^
What is message though?
Sorry for interrupting, I looked up how cogs works and it doesn't seem like I want to use this since from what I understood you can't separately do a command handler and a event handler
You can tho? What did you look at?
Try printing message.content.
A few posts on stackoverflow, and googled how cogs works with python, I haven't found a site where they explain how to make separate handlers using cogs
Example for using cogs in discord.py. Contribute to ScopesCodez/discordpy-cogs development by creating an account on GitHub.
I've explained it in this repository.
Oh okay ty
Im trying to make a report command, and I want users to be able to send proof pictures and let that pictures be send to the logs channel. But Is that possible at all?
Or Is It just message.content?
!d discord.Message.attachments
A list of attachments given to a message.
Gives a list of attachments (pictures in your case)
@commands.command(brief="Iemand reporten", description="Iemand reporten voor bijv leaken of raiden")
async def report(self, ctx, user=None, proof=None, reason=None):
botmessage = await ctx.send("Wat is de discord naam en tag?")
message = await bot.wait_for("message")
user = message.content
await message.delete()
await botmessage.edit(context="Kan je hieronder **1** foto sturen die het meest bewijst?")
message = await bot.wait_for("message")
proof=message.content
await message.delete()
await botmessage.edit(context="Wat is de reden dat hij gereport wordt?")
message = await bot.wait_for("message")
reason = message.content
await message.delete()
await botmessage.delete()
await ctx.send(f"Je report over {user} is succesvol naar het management verstuurt, {ctx.author.mention}")```
The message doesnt edit
hey
content, not context when editing
And you shouldn't just accept screenshots as proof, they can be faked
How can I get a guilds information?
!d discord.Guild has all the attributes you need
class discord.Guild```
Represents a Discord guild.
This is referred to as a โserverโ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildโs hash.
str(x) Returns the guildโs name.
ya the thing is I can't use discord.Guild since i do
from discord.etx import commands```
do i do commands.guild?
then do
import discord
``` since `.Guild` is from the `discord` module and not the `ext.commands` module
๐
how can i install discord.py 2.0 in replit? I need it because i think threads only works in 2.0 or later
<discord.embeds.Embed object at 0x000001F95F709700> this is the output i get from:
@commands.command()
async def guildinfo(self, ctx):
embed = discord.Embed(title="Guild Information")
embed.add_field(name="Guild Owner", value=f"{discord.Guild.owner}")
await ctx.send(embed)
How come?
it's ctx.guild.owner in commands
oh ok
guild
pip install -U git+https://github.com/Rapptz/discord.py
I still get <discord.embeds.Embed object at 0x000001E6C5249700>
thanks
show me wut u did
await ctx.send(embed = embed)
oh
@commands.command()
async def guildinfo(self, ctx):
embed = discord.Embed(title="Guild Information")
embed.add_field(name="Guild Owner", value=f"{ctx.guild.owner}")
await ctx.send(embed)
hm
@slate swan
oh, what does this do tho?
yes try
what does the code do? like why do i do this? (so i can learn)
it returns the guild owner
since there was ctx as a param it'll return the guild owner from where the command was invoked
no no, the (embed = embed) why do i do that
when u send embeds, u cant send it directly. u have type embed = embed name to send it
embed name means the name of ur embed variable
okay so the second embed is my variable i get that, but what is the first embed
Guys what type of mini games should I do using discord.py?
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
no the first embed is just akeyword not a variable
*a key word
i think its to clarify what embed your using @slate swan not sure though
or this
since embed could be anything
ctx.guild.owner.name maybe
or the server is glitched
!d discord.Guild.owner
property owner: Optional[discord.member.Member]```
The member that owns the guild.
it's a bug
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.
intents?
^ since owner is a member object and your bot needs certain things to access those
just go to the dev portal > applications > bot > intents
yes its on
Yes but if you send a message with ctx.guild.owner it should return a member object
Enable intents and active them when you declare your bot object
I enabled them already
try doing this but intents=discord.Intents.all()
It says create_thread is not defined. i am in 2.0
use ctx.channel
Did you pass intents on your bot?
yes
yes
Then is a bug probably
ok
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.
New in version 2.0.
Try on another guild
main.py```py
from discord.ext import commands
from discord import Intents
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix="-")
commands/guild.py```py
@commands.command()
async def guildinfo(self, ctx):
embed = discord.Embed(title="Guild Information")
embed.add_field(name="Guild Owner", value=f"{ctx.guild.owner}")
await ctx.send(embed=embed)
theres this bug where if your the owner and give yourself 2 roles with admin and one without admin you'll lose the server "crown" icon and I think that affects discord.py but im not sure
You did not pass the intents to the bot
@slate swan i want my bot to say sth in voice channel
i followed the docs you guys sent in this channel
bot = commands.bot(prefix=. . ., intents = intents)
gets ignored
๐ข
why is this error happening?
you need to specify a type
I did not try it but i think that the bot search for who created the guild
guild = self.bot.get_guild(data["guild"])
member = guild.get_member(data["userid"])
Ok so
When i print member its None
Which shouldnt be None cause its my id and im in the server
Its not finding me
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Yes
Its from my database
Im using mongodb
When i print the data["userid"] my id shows up perfectly
Its a int
So i dont know whats wrong
It is an int object or str object?
I said its a int
What
Did you know Converters?
How do i get a member object when it returns none
no
You are using guild.get_member method, Converters are a class which convert data into an object
Try doing this, import discord.Member and do member: Member = data["userid"]
Then print it
typehinting only works in your command parameter, doing that doesn't automatically convert that int to discord.Member
just enable members intents
I do have member intents on
They work for me lol
discord.TextChannel always returns a channel and throws an error if it's not found?
Yes
Hi, so I would need if person 1 is typing on server a in global channel that the bot starts typing on all the other servers too in the specific channels that is in a list. can someone help me?
Okay thanks
no they dont, it calls MemberConverter in context.prepare, which doesn't exist if you typehint it like that
Buddy i have a command where i have to convert a role id from by database and i did it in this way .-.
i can tell you that's not even the converter doing it
Well bruh, till it works, don't touch it ๐ ๐
just saying since you're giving wrong info there
Typehints do absolutely nothing unless something additional is present to make them work. In the case of discord.py, the decorators include this functionality, which is why the type hints on your parameters are enforced
But they're not going to be enforced if you just have some variable definition somewhere in your code
@commands.command()
@commands.is_owner()
async def reload(self, ctx, *, name: str):
if ctx.message.content[1] == "cmd":
try:
self.client.reload_extension(f"commands.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**commands.{name}** reloaded!")
elif ctx.message.content[1] == "event":
try:
self.client.reload_extension(f"..events.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**events.{name}** reloaded!")
else:
try:
self.client.reload_extension(f"..{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**{name}** reloaded")
How come this isn't working man i've been stuck on this for a while now, I dont understand the issue, it returns the exception everytime
It's been a while since I've used discord.py, but iirc ctx.message.content is just the message content in a string form. Which means that ctx.message.content[1] is just grabbing the character at index 1, which can never be equal to a string of length greater than 1
You probably meant to check name
if name == "cmd": etc
ctx: commands.Context ๐ง
i have these files:
commands โ
guildinfo.py
reload.py
events โ
on_ready.py
main.py
so the thing is I want reload to be able to reload in events, commands and the files outside these folders such as main.py
so, when i run the command -reload cmd guildinfo it will reload the guildinfo.py in commands folder
if i do -reload event on_ready it will reload the on_ready.py in the events folder, but if i do -reload main its supposed to reload the main.py
^
My point still stands, ctx.message.content[1] is just getting the character at index 1 of the message content, which will never be equal to cmd or event etc
Can someone help?
That would make a list of characters, not a list of words
!d discord.on_typing
discord.on_typing(channel, user, when)```
Called when someone begins typing a message.
The `channel` parameter can be a [`abc.Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") instance. Which could either be [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel"), [`GroupChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.GroupChannel "discord.GroupChannel"), or [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel").
If the `channel` is a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") then the `user` parameter is a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"), otherwise it is a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
This requires [`Intents.typing`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.typing "discord.Intents.typing") to be enabled.
You could split it, but just make a second argument instead
Pass in the event as a param as well as the name
i tried that too but then it threw me an error saying missing argument in reload() when i dont wanna reload in any folder
Make it an optional arg (you'll need it to be the last argument if this is the case however)
Yeah, but I really have no Idea on how to do that
how do you define a optional argument?
async def reload(self, ctx, *, name: str, event=None):
If it's not given it'll be set to None
user returns the person who is typing, so u can check if user is an instance of discord.Member . If it is, then u can get the channel he in typing in, with the channel param
Okay thanks
My start
@bot.event
async def on_typing(channel, user):
if channel in servers:
how do I trigger the typing?
It accepts 3 args
Also channel returns the TextChannel, not the server
U gotta get the server with channel.guild
And then?
@bot.event
async def on_typing(channel, user):
if channel.guild in servers:
Like that? @maiden fable
still wont work man im going crazy xD
It accepts 3 args
See the embed Python bot sent
@commands.command()
@commands.is_owner()
async def reload(self, ctx, *, name: str, filename=None):
if filename == "cmd":
try:
self.client.reload_extension(f"commands.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**commands.{name}** reloaded!")
elif filename == "event":
try:
self.client.reload_extension(f"..events.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**events.{name}** reloaded!")
else:
try:
self.client.reload_extension(f"..{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f"**{name}** reloaded")
E.S โ Today at 1:35 PM
-reload guildinfo cmd
Misa BOT โ Today at 1:35 PM
Extension '..guildinfo cmd' could not be loaded.
yeah, added it. And now?
Uhhh, lemme see what u want to do
Ah, just do channel.trigger_typing
!d discord.TextChannel.trigger_typing
await trigger_typing()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Triggers a *typing* indicator to the destination.
*Typing* indicator will go away after 10 seconds, or after a message is sent.
@slate swan Odd, it seems it just accepted guildinfo cmd as a single arg. It's entirely possible I'm just misremembering and discord.py is just going throw everything after *, into the one param. Like I said it's been a long time since I last used it.
I gotta go, but someone should be able to help you out with getting those arguments separated properly
*, arg puts everything not already consumed into arg
So you won't get away with adding arguments after it
hi
@bot.command(pass_context=True)
@commands.is_owner()
async def shutdown(ctx):
await ctx.author.send('Hazard shutting down...')
await ctx.bot.logout()
how to i add extra owner?
owner_ids kwarg in the bot constructor accepts a list of owner IDs. Also, the pass_context thing is old now
I have written code to automatically create a channel when a user joins the server,
but when the user leaves the server, can I automatically delete the created channel?
U gotta store the channel in something
Like a DB or a dict (cache)
I see
I was wondering if I can do a coroutine for another try/except inside an async def. For instance, when it comes to buttons, you have to use try/except to time out an expiration to components at a certain moment. But for my case, once you press a button, it prompts an ephemeral embed with another component attached to it, I was wondering if I could use two try/except in a asynchronous way (so their own respective components expire independently) instead of a try/except inside a try/except which one depends another.
what
btw how do you make a bot create a thread
hello
i have send a embed message. i can fetch the message and change only something like title or description?
will change my whole embed?
Is it just for me or is the random api down?
nope
it will only change the certain thingy(Eg. desc/value)
you can change anything on there
anyone know how i can make my boy embed a message on join
on_join event
hey guys, I am working on a music bot, I'm currently using yt-dl to source the audio, is there a way to use Spotify or some other source with a better audio quality for the same?
its okay i taught myself how xd
I would like to set permissions for a channel after it is automatically created.
How can I get the Id of the newly created channel on the fly to write the code to set the permissions?
hey can anyone tell me how can i send a msg from my bot with second line
like
my prefix is g
type g help for more info
you could set a variable and await create channel with the variable
async def on_message(message):
mention = f'<@!{bot.user.id}>'
if mention in message.content:
await message.channel.send("Ya can type g help for more info")```
i was making my bot do this command on ping but how do i add second line?
Could you please tell me the detailed method?
what do you mean "2nd" line ?
nvm i was using / instead of \
#you could do it by
channel = await #codeblock
I'm not a good explainer , I'm still learning
if ctx.channel == True:
return
Is this correct? I want to make sure you are talking to the bot privately not in a s ever or channel
talking to a bot in dm?
what were you trying to do at first?
Ohh i get it now
Yes
one qustion how do u guys make a uhm like when somone pings the owner for example lemon his the owner and i want my bot to say Sorry please ping the Admins
So can u help me?
from discord.ext import commands
Bot = commands.Bot(command_prefix=".")
@Bot.event
async def on_ready():
print("Bot is Ready")
@Bot.command()
async def hello(ctx):
await ctx.reply("Hello")
@Bot.command()
async def add(ctx, numb1:int, numb2:int):
await ctx.reply(numb1+numb2)
@Bot.command()
async def multiply(ctx, numb1:int, numb2:int):
await ctx.reply(numb1*numb2)
@Bot.command()
async def divide(ctx, numb1:int, numb2:int):
await ctx.reply(numb1/numb2
Bot.run("tokenpastedhere")```
why does it throw error
bc u didnt close the ) at the divide command
๐
Someone can help me with requests?
sure?
requests the library i mean
mh ask one of the @zinc trench or @slate swan
ohh yes why am i dumb
i jusr a biginner started learning i dont know tbh
mh
Error?
got it
Is it related to a discord command?
๐
Check the message content
!d discord.Message.content
The actual contents of the message.
Yes
I could help. Show me the code
i dont have one bc idk how to make it works
Like i know discord.py very well
but i dont know how to use requests for make HTTP GET
hm
Im trying to get data from an api
you can get the "data" from the api if the api is a json link. by doing
a = requests.get(url)
``` then doing
```py
e = await a.json()
``` iirc
is a site where you need to vote how i create a variable like {votesTotal}
for get the n of votes?
i meannnn sure I guess
.
well use the way I said earlier and get the json data from the url if it even is json
but can i do that in vscode?
i dont want to use repl.it
vscode and replit is an IDE
so yes, you can.
can u help me i wrote this code
sure I guess
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.getenv("token")
Bot = commands.Bot(command_prefix=".")
@Bot.event
async def on_ready():
print("Bot is Ready")
@Bot.command()
async def hello(ctx):
await ctx.reply("Hello")
@Bot.command()
async def add(ctx, numb1:int, numb2:int):
await ctx.reply(numb1+numb2)
@Bot.command()
async def multiply(ctx, numb1:int, numb2:int):
await ctx.reply(numb1*numb2)
@Bot.command()
async def divide(ctx, numb1:int, numb2:int):
await ctx.reply(numb1/numb2)
Bot.run(token)```
whats wrong?
Try doing ctrl shift p and show me what pops up
lol this pops up
search "select linter"
re = data['mutetime'] - 1
if data["mutetime"] != 0:
await collection.update_many({"same": "pog"},{'$set':{'mutetime': re}}
How do I only respond to a certain word IF they tell that word to the private chat with my bot?
Ok so this is in a tasks that loops for 1 second it subtracts 1 from a int
click pylint
It works with the same person only
check if the channel was a dm channel > check the message content
Only problem is when a different person gets in the database and has a different mute time
shall i install it
yes
It pretty much puts the mute time of the first person
should i install github copilot
done wow
Oh ok but how
To the other dude and i dont really know how to individually subtract 1 from each of their mute time simultanously
Did it work?
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelโs hash.
str(x) Returns a string representation of the channel
yes so now i how do i add token
?by creating an env file
Wow thx
uhmm check the stack overflow earlier
.
something like
if isinstance(message.channel, discord.DMChannel):
if ... in ...:
#code
btw @boreal ravine why are you so intelligent ๐
Thx
create a file called .env create a variable named token or whatever you want it to be (the token doesn't need to be in a string) and in the main file do token = os.getenv("token") or bot.run(os.getenv("token"))
Im using mongodb for the database
i made .env file and added token = pastedtokenhere
then when i run code in main file
it says
AttributeError: 'NoneType' object has no attribute 'strip'
i did it but now how i get the specific data i want?
printing the json show me all the datas
click the link > index the data you want
example?
Show full error
like data["money"]
You can't do = and += lmao
full traceback?
like @bright palm said use += only
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.getenv("token")
Bot = commands.Bot(command_prefix=".")
@Bot.event
async def on_ready():
print("Bot is Ready")
@Bot.command()
async def hello(ctx):
await ctx.reply("Hello")
@Bot.command()
async def add(ctx, numb1:int, numb2:int):
await ctx.reply(numb1+numb2)
@Bot.command()
async def multiply(ctx, numb1:int, numb2:int):
await ctx.reply(numb1*numb2)
@Bot.command()
async def divide(ctx, numb1:int, numb2:int):
await ctx.reply(numb1/numb2)
Bot.run(token)```
see my code
i meant the full error not the code
thx
thx
https://api.minecraft-italia.it/v5/server-info/nameserver?key=APIKEY where i need to put the data i want @boreal ravine
i just removed my apikey and the nameserver
Traceback (most recent call last): File "c:/Users/pnbha/OneDrive/Documents/Python/Discord/bot.py", line 31, in <module> Bot.run(token) File "C:\Users\pnbha\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 723, in run return future.result() File "C:\Users\pnbha\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 702, in runner await self.start(*args, **kwargs) File "C:\Users\pnbha\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 665, in start await self.login(*args, bot=bot) File "C:\Users\pnbha\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'
It's cause the environment variable doesn't exist
do u have a variable for the json link thingy
So it is getting the default which is None
did you create a file called .env?
yes
whats it called
voti
yes see this .env file has token
so if the json was like this
{"statusCode":404,"message":"Questo server non esiste","error":"Not Found"}
``` you'd do
```py
print(voti["statusCode"])
print(voti["message"])
print(voti["error"])
``` & more
i created .env file still error
You are using vscode right?
Is your .env in the base folder
Of your current workspace
Can you show your folder tree
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/cogs/general.py", line 291, in on_raw_reaction_add
if embed.colour not in utily.color:
TypeError: argument of type 'int' is not iterable
if embed.colour not in utily.color:
return
i just created new file and named it .env๐
And this is the root folder?
nope wait sorry forgot to send whole folder
.-. have it open as the root folder or put the .env in the Python folder
ohh
lemme try
@bright palm
like this?
still showing error
it was runnnig smoothly then suddleny this happened
it happened with me once i closed whole thing and started again and it worked
lol
are u using env too.
yeah ,
oh
yeah i can show u
does a "Token" key exist?
yeah
@ionic ledge try ["Token"] then
okay
;-;
i mean , i need to wait for a reason i dont know
Replit moment
Thatโs replit right?
Replit has been used to host a lot of spam bots and discord is quickly banning all their IPs
So you cannot use replit, not that you should in the first place
Been using replit for about 4 months now and I have never seen that error ยฏ_(ใ)_/ยฏ
Just wait until your node is used by spambots
Then it will quickly be banned
^
A node?
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
The physical machine
Itโs called a node when youโre talking about servers
- The machines are super underpowered.
- This means your bot will lag a lot as it gets bigger.
- You need to run a webserver alongside your bot to prevent it from being shut off.
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
- This means any file you saved via your bot will be overwritten when you next launch.
eh i can easily bypass the "file part" and my bot isnt that big anyways
Be warned that there is a fair chance you will literally have your account banned from discord
for what reason
Your bot is on a machine that was used to send spam attacks
eh. I'll keep that in mind.
so where can i host my bot for free
You donโt
is there any function to handle errors caused by Cog.listeners()
Well some would say their own pc or self hosting is free, if you donโt count electricity bills
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.9)").
If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.9)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
i did try the on_error function it did not invoke
how did you implement it?
class Test(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self,message):
a = 10/0
print(a)
@commands.Cog.listener()
async def on_error(self,event,*args,**kwargs):
print(event)
print(args)
print(kwargs)
def setup(bot):
bot.add_cog(Test(bot))
is it wrong
i am new with discord bot programing and no idea how args and kwargs work
learn args, kwargs first
args and kwargs are literally that, args and kwargs
arguments and keyword arguments
*args and **kwargs means it will take any argument and any keyword argument, no matter how many
so is the syntax correct for the above function
hm i just tried it, for some reason on_error indeed isn't dispatching, and i have a feeling i might know why
since on_error is a built in event
its , on_command_error
yes on_command_error works only for commands
hmm from my testing, the only thing i can suggest now is wrapping possible erroring code in try except statements
oh ic
since on_error seems to work differently
!d discord.on_error but it's discord.on_command_error for commands
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.9)").
If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.9)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
i tried it with this simple test code
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
class Test(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self,message):
a = 10/0
print(a)
@commands.Cog.listener()
async def on_error(self, event, *args, **kwargs):
print(event)
bot.add_cog(Test(bot))
bot.run("TOKEN")
and it did not work
maybe this is revalent
ah yeah that makes sense
so it can only be dispatched to bot.event() and not to cog.listener()
ye
any error handler function for listeners
what kind of errors are you actually trying to handle?
i am creating a function if any error happens the bot will dm me what error has occured
im asking , what kind of errors do you expect?
if an error in an command , use on_command_error
hey there, actually I was facing some errors, I had put some member ids in a blacklist.txt file, and I wanted the bot to not respond when a member id is in blacklist.txt file. Which wasn't really executing correctly
@commands.Cog.listener()
async def on_command(self, ctx):
print(ctx.command.name)
f = open('cogs/blacklist/blusers.txt').read()
blusers = f.split('\n')
print(blusers)
if str(ctx.author.id) in blusers:
print("Error")
return
you will need to overwrite the built in on_message event
this wont stop the member from using the command
on_command runs when someone uses a command, but it's unable to stop the command's exeuction
umm, can u tell me how can I do it?
not determined
use a check , or do what sebkuip said
yeah, that is the thing
or a global check works too
yes
!d discord.ext.commands.Bot.check
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
checks is the best option
ahh I see, I'll get back to u, after trying it out!
runtime errors
have u used "await" where ur getting the error?
for your commands?
for listeners
hey umm, I got this error
discord.ext.commands.errors.CheckFailure: The global check functions for command help failed.
can u show me the code, maybe I can help
umm, I don't quite understand you
also
how can I fix it
this means you used a global check, and the check failed, as in it didn't allow the command to run
for example one listener function in cog deletes a message and another listener function in other cog receives an error
ohh I see, is there a way to fix it?
and how?
there's no fix if there's no issue
you set your check to fail in this situation, and it failed, stopping the command from running
@slate swan
it's only raising an error so you can handle it if you want, to inform the user the check failed, or do whatever you want
is there any way to fix that
@valid niche I found the thing which was giving that error and fixed it, now my code runs without any errors, but the thing is now the user is able to msg, even when his id is in blacklist.txt
Discord.py is shit man
nope, it isn't but libs like nextcoord and pycoord are taking over it
https://discordpy.readthedocs.io/en/stable/api.html?highlight=client#id7 (User docs)
https://discordpy.readthedocs.io/en/stable/api.html?highlight=client#member (Member docs)
I cant find a attribute to get a member/users full username with the hashtag
str(user)
its ctx.author only
author IS the user
^
or rather, it's the member in most cases
the only times it's a user is when the member left before ctx was created, or it's in DMs
i created an afk command but when i set afk
async def afk (ctx, reason = None):
current_nick = ctx.author.nick
embed = discord.Embed (title = "AFK", description = f "{ctx.author.mention} is now ** AFK ** - ** Reason: {reason} **", color = 0x00ff00)`
await ctx.send (embed = embed)
await ctx.author.edit (nick = f "[AFK] {ctx.author.mention}")```
when the user is put afk, the id of the person is shown with afk, when I used `ctx.author.mention instead`
@river kindle y pass context
ah?
also those spaces in the decorator are also...uncommon
it's not exactly normal to write it all with spaces
oh and one last tip: according to good naming conventions, client.command is NOT possible to exist
it would be bot.command
having good naming is important
whats wrong tho
client.command exists๐ซ
read again
according do GOOD NAMING CONVENTIONS client.command shouldn't exist
Meanwhile I'm already here, https://paste.ofcode.org/39naEBrt7R26i8rmiM3wg9n
How can I make my reload command shorter? I use multiple if statements and multiple embeds (im going to add embed to the exception errors too), so there has to be a way of shortening this right?
!zen 2
Simple is better than complex.
if message.content.startswith("$ryv"):
ryv = randint(1,10)
if ryv == (1):
ryv = [
"https://www.youtube.com/watch?v=3_wbWSlxG4A",
"https://www.youtube.com/watch?v=oyCYrCG0_MA",
"https://www.youtube.com/watch?v=ZU7Q2yvmwfc"
]
await message.channel.send(ramdom.choice(ryv))```
or not zen 2
what do i wrong
which zen was it
lmao
@devout quest bruh
!zen 7
Special cases aren't special enough to break the rules.
ur variable names
!zen 6
Readability counts.
there we go, that was it
if message.content.startswith("$ryv"):
ryv = randint(1,10)
if ryv == (1):
ryv = [
"https://www.youtube.com/watch?v=3_wbWSlxG4A",
"https://www.youtube.com/watch?v=oyCYrCG0_MA",
"https://www.youtube.com/watch?v=ZU7Q2yvmwfc"
]
await message.channel.send(ramdom.choice(ryv))```
what
Meanwhile I'm already here, https://paste.ofcode.org/39naEBrt7R26i8rmiM3wg9n
How can I make my reload command shorter? I use multiple if statements and multiple embeds (im going to add embed to the exception errors too), so there has to be a way of shortening this right?
if you could state your issue
uh, why
because
help me debug
ryx is already set to a random int
fix my code
no
that is ryv
why exactly do you wish to shorten it?
when a user requests ?afk the bot sets his name to [AFK] and his user id when in fact he should put his current name to afk
please state the issue you are having
you could add a param and then load the "extension" using the param name
saying "it doesn't work" isn't enough information
I don't want to repeat the embeds and the if statements, normally i would use for in loops but idk what to do in this case
yes but whats wrong? the bot cant change names?
no, the bot manages to do that, but how did I present that problem to you
help?
async def on_message(message):
def check(m):
return m.channel == message.channel and m.author != client.user and "__Super Rare__" in m.content
embeds = message.embeds
if not message.embeds:
await client.process_commands(message)
return
footer = (embeds[0].to_dict()['footer'])
if "Type" in footer:
m = await message.channel.send("")
while True:
response = await client.wait_for('message', check = check, timeout=300)
if "__Super Rare__" in response.content:
break
await message.channel.send("")```
How do i end this i have no more codes
whats the problem though
the code looks fine
https://paste.ofcode.org/39naEBrt7R26i8rmiM3wg9n
How can I make my reload command shorter? I use multiple if statements and multiple embeds (im going to add embed to the exception errors too), so there has to be a way of shortening this right? I dont want to repeatedly use embeds and if statements
@slate swan
@slate swan also stop reposting stuff
I know, but it doesn't work
already what ive done?
what doesnt?
no
im asking how I can shorten the if statements and embeds?
you have an if statement
that checks for certain files
my way is that u check
for every file in the arg given
no you havent understood the code
so no need for "if statements"
async def reload(self, ctx, name: str = None, filename: str = None):
I have 2 args, one folder and one for the file to reload
which part
@cunning lion
ping ๐
if you wanna shorten the embeds/lines you can send it in one line
nah I don't think you understand what I meant by repeatedly calling discord.Embed
Idk how to explain tbh
nvm ill fix it by my own ty tho
ctx.author.mention does not mention the user's nickname together with [AFK]
ctx.author.mention mentions the user
im trying to use ctx.author.name
if he had a nickname it'll show up
use display_name
to display nicknames
nice
thanks @boreal ravine
any help
how do i get a list of all the members in a server
!d discord.Guild.members
property members: List[discord.member.Member]```
A list of members that belong to this guild.
im trying to print the list out:
print(ctx.message.guild.members)
but that returns this for some reason:
[<Member id=863786161600462918 name='Tebby' discriminator='5433' bot=True nick=None guild=<Guild id=server_id name='ServerName' shard_id=None chunked=False member_count=1792>>]
what am i doing wrong
it returns the member objects as you can see , iterate through the list and use the attribute that you need
async def on_member_join(member):
embed = discord.Embed(colour=0x000000, title=f"Welcome to kiss!", description=f"There are now {len(list(member.guild.members))} members "),
embed.set_thumbnail(url=f"https://cdn.discordapp.com/icons/721726753147453583/a_e9109e9fbf8e0ecf8613cc5bb8515228.gif")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar_url}")
channel = client.get_channel(id=896885653713870848)
await channel.send(f'{member.mention}', embed=embed)``` not working when i have a dm on member join
any1 know why?
turn on intents
they are tho
lemme make sure tho hold on
oh wait , why would the embed be sent to user when you are sending it to a channel according to your code....
i have a seperate one that sends an embed to dms
you should send that code then?
@client.event
async def on_member_join(member):
print ("{} joined!".format(member.name))
print (f'{member.guild.name}')
role = member.guild.roles
if member.guild and not member.bot:
async with member.typing():
embed = discord.Embed(
title="Welcome to Kiss!",
colour=0x000000,
)
embed.set_thumbnail(
url="https://cdn.discordapp.com/icons/896885629391106080/a_b6b1f08f67118dc828195dcdc35b0f3d.gif"),
embed.add_field(name="Make sure to read the rules and get some roles!  ",
value="We are a small Edating, Aesthetic, NSFW server. ")
embed.set_footer(text="Dm zul#1337 for help")
await member.send(embed=embed)```
so , the bot types in the member's dms?
send a embed then shows it as typing
im not sure , but you cannot have 2 same events
ah, so do you know what i should change it to?
change it to a listener
replace .event to .listen() and try
@client.listen() yes?
hm sure
alright gimme a sec
you have an extra , after color =
remove it
it must be <a textchannel object>.create_thread(......
ctx.channel.create_thread?
sure if you want to create a thread in the same channel
under which
your embed = discord.Embed
you are not , replit wont use discord.py2.0 for sure
@valid niche
not this one , here py f member.guild and not member.bot: async with member.typing(): embed = discord.Embed( title="Welcome to Kiss!", colour=0x000000, ) embed.set_thumbnail(
in the code you sent above
ohh
again: the error was literally only there to say "hey the check failed, the user wasn't able to use the command, here is an error so you can inform the user"
it's not an actual error that you made a mistake
so you want me to remove the , in this?
so if you "fixed" that error, that means you removed the check
remove the , after that
since you have no more kwargs there
it says 2.0 i cloned the github repo
uhh, I see, but the thing is, when it doesn;t work, then id doesn;t work for anyone, and when it does work, then it works for everyone
@check
async def on_command(self, ctx):
print(ctx.command.name)
f = open('cogs/blacklist/blusers.txt').read()
blusers = f.split('\n')
print(blusers)
if str(ctx.author.id) in blusers:
print("Error")
return
?
I want to make it so if you use a command a role gets removed from yourself, dm me if u know how thanks :0
try printing discord.__version__ and show what it returns
@slate swan u sure thats a valid hex code?
yes 0x000000 returns black iirc
yeah its black
@ocean leaf try ctx.channel.create_thread()
I want to make it so if you use a command a role gets removed from yourself, dm me if u know how thanks :0
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
wont it still work with & without that
does discord.Role.members require member intents? ๐ถ
you should return True or False, not just return
!e print("hi",)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
hi
not , it becomes a tuple
as the error says
return True means the command may run, return False, or anything else means the command may not run
!e print(type('hi',))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'str'>
owh
I tried them already, same thing as before
!e a = "a",; print(type(a))
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
<class 'tuple'>
i see , was that because type function was not treating the tuple as a tuple but just an argument in brackets?
how do I make environment variables work?
type is not a function but yes
did u use checks
yeah, ofc see the code
custom checks
i meant the type(object) function
type is a class
umm, no, actually I don't want any of the blacklisted users to execute any command, I mean how can I go adding checks to every command
you should return true when the check passes, and the user is allowed to use the command. You should return False if they are not allowed. This will cause a checkfailure error, which you can handle to inform the user that they are not allowed
that's how the intended setup is
Today we remove our messy command decorators and make it into one custom check.
Read description for links!
----------------------------------------ยญยญ---------------------------------------ยญ-ยญ--
Need Help?
Require help with your code? Why not head on over to our dedicated support discord where you can recieve only the best support: https://me...
ahh I get it now
take this video
hmm
u can add role checks like has role blacklisted which will make your code simpler
@inner geyser did it work
what;s line 129
๐
How i can parse Member.roles so it returns me only a list of role names?
you need to iterate thru it
worked. now just gotta see why the dm embed isnt sending
Parsing it isnโt really the correct term for it, but you can use a comprehension to get the role names from each of the role objects
I can treat them as a list of tuples?
ofcourse discord.Guild.member returns an list
@placid skiff this was for u ^
wrong ping
!list-comp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if statement:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
You should do this
I try
And u can do role.name for role in...
async def reload(self, ctx, folder: str = None, file: str = None):
ftype = {"commands": "cmd", "events": "event"}
for f in ftype:
if folder in ftype or folder in ftype.values():
try:
self.client.reload_extension(f"{f}.{file}")
except Exception as e:
return await ctx.send(e)
await ctx.send("successfully reloaded")
break
if folder not in ftype or folder not in
await ctx.send("invalid arguments")
break
``` When I type event instead of cmd, it wont work because it's only iterating through the first key, how can I fix this?
Try printing ftype.values()
???
you will help me resize and make the avatar under the overlay
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
๐จNote: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
Don't. Just don't use replit
Sorry never used PIL or Pillow =(
You said it's iterating only through the first value, and not reaching the second one, so I am saying try printing it
Yeah I already know why it's not doing this, but I dont know how to solve it
Tell me why it's not doing it then....?
you can use <the image instance>.resize( height , width) to resize an image
but pasting the overlay at a different scope seems a better option
I guess many people? Also try opening a help channel since this channel is specifically for help with Discord API Libraries and you would have more chances of someone helping you in a help channel
but my point is to reverse the order of the objection
it's because it never can reach the second iteration because i break the loop, and if i dont break the loop, it will print twice, and on the second iteration it will raise an error because the path for the reload_extension() will be wrong
to which channel?
Why do u have the last if statement inside the loop...?
i tried having it outside, it made everything worse
Also why don't u just do if folder in ftype.keys() or folder in ftype.values()?
Why u looping
because i need the f
im declaring the path
for f in ftype:
if folder in ftype or folder in ftype.values():
try:
self.client.reload_extension(f"{f}.{file}")
Can't u simply use regex or something like folder.replace("command.", "cmd.") or something?
if its a cmd, f = "commands", if its a event, f = "events", but for it to be events, it needs to reach the second iteration which it doesnt
Don't ping mods or helpers randomly
sorry
Ghost Ping ๐
i solved this using lambda in the end lol
Lol cool
In what way did you use lambda?
Just curious
i used discord.utils.find to search for the role in the list of roles
hey guys im trying to make a bot where if u type a command and u have a certiain role then it removes your own role
@commands.has_role('eligible')
async def name(ctx, role: discord.Role, user: discord.Member):
yes
It returns 2.0
I couldn't use checks don't worry xD
i'm not stupid
i have to check if a user has a role that is saved in my database
hello?
so until the command is executed i don't know what role that is
Did threads ever get implemented in 2.0?
how to make a music bot?
Yes they did
wow u guys help alot
In 2.9 only
We know what you want to do, but we have no idea what you need help wit
search in google
Well, lets see, you can use Member.remove_roles i believe to remove roles
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
By the way i think i will go Crazy with the next things i want to do
Even if i think that i already know how to do that xD
in that command is the *roles the name of the role
It is a role object
Looks like your command takes a tole object as a parameter, so you should just be able to pass it in without doing anything to it
You can't
You can, but you canโt get verified if you use youtubedl or other stuff
Just donโt use youtube downloaders or other things that are against tos
Yeah
@slate swan ```@client.event
async def on_member_join(member):
print ("{} joined!".format(member.name))
print (f'{member.guild.name}')
role = member.guild.roles
if member.guild and not member.bot:
async with member.typing():
embed = discord.Embed(
title="Welcome to Kiss!",
colour=0x000000,
)
embed.set_thumbnail(
url="https://cdn.discordapp.com/icons/896885629391106080/a_b6b1f08f67118dc828195dcdc35b0f3d.gif"),
embed.add_field(name="Make sure to read the rules and get some roles!  ",
value="We are a small Edating, Aesthetic, NSFW community. ")
embed.set_footer(text="Dm zul#1337 for help")
await member.send(embed=embed)
embed = discord.Embed(colour=0x000000, title=f"Welcome to kiss!", description=f"There are now {len(list(member.guild.members))} members ")
embed.set_thumbnail(url=f"https://cdn.discordapp.com/icons/721726753147453583/a_e9109e9fbf8e0ecf8613cc5bb8515228.gif")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar_url}")
channel = client.get_channel(id=896885653713870848)
await channel.send(f'{member.mention}', embed=embed)``` is this better
how do i make it so that if someone DMs my bot, it DMs me their message and who sent it?
kinda like @novel apex
@client.event
async def on_message(message):
my_user_id = 853991571702939668
user = client.fetch_user(my_user_id)
if type(message.channel) == discord.channel.DMChannel:
await message.channel.send("Hi :)")
await user.send(f"{message.author.name}#{message.author.discriminator} messaged your bot: `{message.content}`")
@fallow mauve that should do it?
music bot?
i think
i don't know if the UPDATE statement returns anything
do you have something to help?
what you could do is generate a UID for each warn, and do it that way maybe?
or ifisinstance()
i used the type because i don't completely know how to use isinstance()
why do you need the update?
why would you want to update a warn
one would think that you just insert a new row for each warn
How exactly?
SQLite is blazing fast
Your code is kind of confusing me because Iโm not sure if UPDATE returns anything
I need help Pls Dm me whoever is good at Python Bot Progamming/Coding.
How can i set the embed color later on?
embed.colour = new_colour
embed doesn't have that attribute tho?
what?
why not here lol
!d discord.Embed.colour
The colour code of the embed. Aliased to color as well. This can be set during initialisation.
its a property iirc
ooh
Is it correct to store data that the bot needs on a json? Or does it has to be a db?
Say for example, data of a minigame my bot has, data of which prefix the bot has on that server, things like that
DB
No hesitation
Does anyone know why my bot keeps restarting randomly? I have logging setup.
It restarts without any errors.
And it happens randomly (after an hour of the startup, 3 hours after that, 10mins after that, etc.)
it re-runs on_ready, and it goes offline on discord for awhile
It shuts off then turns back on but keeps data (like the bot's uptime time)
(Shud I ask this in a help channel)
@slate swan what host do you use?
I tried multiple hosts
Google VPS, WitherHosting, Dynox, Repl.it, Heroku, and even my pc
which one were u using
how can i make loop that checks if there are messages in channel(by id) and then delete all messages
did you set up logging?
