#discord-bots
1 messages ยท Page 812 of 1
ive already done the image part, the message part just isnt working
await ctx.send(file=discord.File('palette.png'))
then everything i put after just threw errors
after this line?
nothing
none of the message code worked
i did await ctx.send(message)
and some others but nothing worked
can you send me errror/code
there is no error for that one, it just doesnt send the message at all
wdym at all
oh its working now
but its just sending 'color' and not the variable values
can you show me code
seding message
await ctx.send(file=discord.File('palette.png'))
await ctx.send(color)
yeh i wanna send the lsit of values
it dont
try this ```py
await ctx.send("\n".join(color))
what does the join do?
joins elements of list to the "\n"
ahhh
so every element will be separated with enter
you can just put " " if you want it in one line
gave an error
TypeError: can only join an iterable
What's color?
i removed that part of the code, im so dumb
there
ill use the correct variable and see what happens
but yes thats what color_palette =
color is not color_palette
its sorted now, ty
๐
you ment like ?
colors = [(72, 83, 90), (237, 146, 86), (35, 232, 191), (152, 143, 139), (93, 119, 211)]
print('\n'.join(map(str, colors)))
map(function, iterable, ...)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap "itertools.starmap").
On
its so u can join em cause thay are not strings but tuples
no it does a calculation and gets the colours
color_palette = color_thief.get_palette(color_count=5, quality=10)
Oh I could use map instead of list comps
i only saw this - and it will give error
why i posted that map-thing
So if I had a tuple of ints and I wanted them to be strings could I use map() to change them?
!e
ints = (72, 83, 90)
print('\n'.join(map(str, ints)))
@honest vessel :white_check_mark: Your eval job has completed with return code 0.
001 | 72
002 | 83
003 | 90
@final iron^
I was using list comps for that
Ill change them to map
!e
print(map(str, (123, 1, 4567)))
@final iron :white_check_mark: Your eval job has completed with return code 0.
<map object at 0x7f8325ed9570>
What did I do wrong
you have to join it.
yeah
I do want to still have a tuple/list though
Cast it.
Example?
list(map(str, [123, 456]))
Ah
?
print(list(map(str, ints)))
oh already answered
We donโt help with self bots here
Iโm not asking for help lol
Especially if they are a discord self bot
It was just a theoretical question
Which should I use:
list(map(str, [123, 456]))
Or
[str(i) for i in my_list]
Chill out dude
dek would say 2 ๐ฟ
Writing code on phone is pain
Does yagpdb custom Command use python?
Legit
idk might use JS or Go
actually I think it does use Go
A dam
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Iโm not doing anything my god ๐
Is it hard?
It was simply a question
if you dont need a list,
for integer in map(str, [1,2,3,4]):
print(integer)```
Just because a successful discord bot was made with Go doesnโt mean you should just jump to that language
I need the list
learn languages that will help you in what you want to do
so my bot prints this to console fine:
for color in color_palette:
print(webcolors.rgb_to_hex(color), end=",")
but when i try send it as a message without the print, it gives an error
So which one of those should I be using
What's the error
says that 'end' is un expected
end is for print only
but if i leave it it goes on new lines
so would i format it instead?
as i want it all to be on 1 line
for color in color_palette:
hexVal = (webcolors.rgb_to_hex(color))
so then i just join hexVal at the end?
@bot.event
async def on_message(message):
if message.guild.get_member(569280782753988608) in message.mentions:
await message.channel.send('freshman895')
await bot.process_commands(message)```
why doesn't this work?
it want it so that if i use bot command and then ping a specific person, it replys with a specific messaage
pls I need a help can somebody come front
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
so what do i change in the code?
Try checking the id I guess
I mean check the id against the elements in the list ids
You could use a normal for loop or a list comp
oh
@bot.command()
async def hug(message, user: discord.Member):
hug_scenario = f"{message.author.mention} gives {user.mention} a warm hug!"
if user.mention == message.author.mention:
await message.channel.send("Aw, don't have any friends to hug? Here's one from me :people_hugging:")
try:
if user.mention != message.author.mention:
await message.channel.send(hug_scenario)
except discord.ext.commands.errors.MemberNotFound:
await message.channel.send("Mention someone to hug smh...")
why wont it catch an error if i do ?hug myself
maybe something like this?
@bot.event
async def on_message(message):
#if message.guild.get_member(569280782753988608) in message.mentions:
for m in message.mentions:
if m.id in [569280782753988608]:
await message.channel.send('freshman895')
await bot.process_commands(message)
We'll see what happens when you try to hug someone that isn't a user
What error gets thrown
discord.ext.commands.errors.MemberNotFound
i already set up a try/except to catch it
didnt work
@bot.command()
async def hug(message, user: discord.Member):
if user is None:
await message.channel.send("Mention someone to hug smh...")
return
# Rest of code
hmm ill try that
!pypi aiosonic
I saw it
Why not use aiohttp?
lol aiohttp slow???
Yes slower than aiosonic
doesnt work
@final iron actualy i was working on antinuke bot which bans nuker fast when i use aiohttp nuker bypass it with 50bans with threads btw i need to minimize this amount so need something to make faster request
their docs say its 102% faster than aiohttp
the id is the user id of the guy i want to mention
Can their numbers even be trusted?
^
What
is it because of async def hug(message, user: discord.Member)
faster isn't always better
Possibly
because i cant catch the error inside the func
Then what should I do make it more efficient in banning nuker faster
You could create an error handler for the command
how would i do that
i hv
bro it really all comes down to the discord api, no? if the api is down or slow it will take longer?
I wasn't talking to you
Let's start coding in Binary cz it's the fastest ๐
sry
for color in color_palette:
(webcolors.rgb_to_hex(color))
this creates every value spereratley and i want it on the same line so that when i print it, i dint have to use 'end' any help would be appreciated
Go learn C then. It's a pretty speedy language
wht should i use then
yes btw no time i need towork on py
Leave High Level Languages, Use Binary ๐ฟ
Tell people not to give untrusted members permissions to ban people
Wonโt need an anti Nuke if you do that
lol
bruh somethings cnt be controlled by us
what
you mean like giving people perms?
bro its not like a random noob is gonna get mod if its not given to them,
i think i can control who i give permissions to pretty well
@regal pulsarmy bad you will need to use error handler - as you tried
.
ah
@slim ibex some epeople in server cheats there server like admins maybe he wants to nuke mine
can u show error?
raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "myself" not found.
can you share the code?
And how can nuke your server if you donโt give him permissions to ban members
the member you tried to invoke the command with is not a valid member
Some trusted members can get untrusted bruh u dont understand
yeah
@bot.command()
async def hug(message, user: discord.Member):
hug_scenario = f"{message.author.mention} gives {user.mention} a warm hug!"
if user.mention == message.author.mention:
await message.channel.send("Aw, don't have any friends to hug? Here's one from me :people_hugging:")
await message.channel.send("Mention someone to hug smh...")
elif user.mention != message.author.mention:
await message.channel.send(hug_scenario)
Weโre those people really trusted in the first place then?
no ctx?
message
so "myself" needs to be a user name/nick to work atleast
i want it to send await message.channel.send("Mention someone to hug smh...")
if no one is mentioned
user: discord.Member = None```
change this
the add,
if user == None:
await ctx.send("mention someone")```
use whatever you use in place of ctx
@regal pulsar
k one sec
my cogs aren't working
cogs/greetings.py:
import discord
from discord.ext import commands
class Greetings(commands.Cog, name="Greetings"): # We Subclass commands.Cog . if the name kwarg is not passed, the Cog name is taken to be the same as the class name
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener() # just like @bot.event
async def on_member_join(member): # called when a member joins
channel = member.guild.system_channel # get the guild's system messages channel - where welcome and boost messages are sent. You can change this to bot.get_channel(channel_id)
if channel is not None:
await channel.send('Welcome {0.mention}.'.format(member))
@commands.command() # this is how you create a command in a Cog. The same as @bot.command()
async def hello(ctx, *, member: discord.Member = None): # always remember to pass "self"!
"""Says hello""" # command description
member = member or ctx.author
await ctx.send('Hello {0.name}~'.format(member))
def setup(bot):
bot.add_cog(Greetings(bot)) # register the cog
main bot file:
import discord, json
from keepalive import keepAlive
config = json.load(open('config/config.json'))
token = config.get('token')
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
bot.load_extension('cogs.greetings')
keepAlive()
bot.run(token)
uuuugh i forgot that way i tried say if user is None: send msg, return
but anyway here is another way
@commands.command()
async def hug(self, ctx, user: disnake.Member):
await ctx.send(f"Hugging {user.display_name}")
@hug.error
async def on_hug_error(self, ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("Mention someone to hug smh...")
yeah im trying to display a message if no one is tagged
nvrm u can do !hug Emotional Support
.
@regal pulsaryou mean if they like only type !hug
then you can just add a more error
yeah or if they type !hug myself
and dont mention anyone
you can make a subcommand for that
for color in color_palette:
(webcolors.rgb_to_hex(color))
this creates every value spereratley and i want it on the same line so that when i print it, i dint have to use 'end' any help would be appreciated
my cogs aren't working
cogs/greetings.py:
import discord
from discord.ext import commands
class Greetings(commands.Cog, name="Greetings"): # We Subclass commands.Cog . if the name kwarg is not passed, the Cog name is taken to be the same as the class name
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener() # just like @bot.event
async def on_member_join(member): # called when a member joins
channel = member.guild.system_channel # get the guild's system messages channel - where welcome and boost messages are sent. You can change this to bot.get_channel(channel_id)
if channel is not None:
await channel.send('Welcome {0.mention}.'.format(member))
@commands.command() # this is how you create a command in a Cog. The same as @bot.command()
async def hello(ctx, *, member: discord.Member = None): # always remember to pass "self"!
"""Says hello""" # command description
member = member or ctx.author
await ctx.send('Hello {0.name}~'.format(member))
def setup(bot):
bot.add_cog(Greetings(bot)) # register the cog
main bot file:
import discord, json
from keepalive import keepAlive
config = json.load(open('config/config.json'))
token = config.get('token')
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
bot.load_extension('cogs.greetings')
keepAlive()
bot.run(token)
@regal pulsarthis is for cogs but, ```py
@commands.command()
async def hug(self, ctx, user: disnake.Member):
await ctx.send(f"Hugging {user.display_name}")
@hug.error
async def on_hug_error(self, ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("Mention someone to hug smh...")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Mention someone to hug smh...")
Your indentation is wrong
For your class
Your methods are not indented properly
@commands.Cog.listener() should be inside the class
spoonfeeding
doesnt work
it won't if you copy paste
๐
im 99.9% sure its because of user: discord.Member
What
That code was meant for a cog. You'll have to use your brain to figure out how to change it
thats one thing u need to change theres more
whats a cog :/
its a class
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
Hunter no way you just tried that
i see
The cog?
!d intents
for color in color_palette:
(webcolors.rgb_to_hex(color))
this creates every value spereratley and i want it on the same line so that when i print it, i dint have to use 'end' any help would be appreciated
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
Also not a discord bot question
@regal pulsarwell compare mycode vs yours, and find whats diffrent, you need to delete something and edit 1 thing pretty much
it is, im using it in my bot and couldnt figure out how to format it so that the bot could send in 1 line
i see
async with aiosonic.ClientSession(headers = { 'Authorization': f'Bot {self.client.http.token}', 'Content-Type': 'application/json' }) as session:
AttributeError: module 'aiosonic' has no attribute 'ClientSession'
wht to do
pls help
Hmm never used that
my cogs aren't working
cogs/greetings.py:
import discord
from discord.ext import commands
class Greetings(commands.Cog, name="Greetings"): # We Subclass commands.Cog . if the name kwarg is not passed, the Cog name is taken to be the same as the class name
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener() # just like @bot.event
async def on_member_join(member): # called when a member joins
channel = member.guild.system_channel # get the guild's system messages channel - where welcome and boost messages are sent. You can change this to bot.get_channel(channel_id)
if channel is not None:
await channel.send('Welcome {0.mention}.'.format(member))
@commands.command() # this is how you create a command in a Cog. The same as @bot.command()
async def hello(ctx, *, member: discord.Member = None): # always remember to pass "self"!
"""Says hello""" # command description
member = member or ctx.author
await ctx.send('Hello {0.name}~'.format(member))
def setup(bot):
bot.add_cog(Greetings(bot)) # register the cog
main bot file:
import discord, json
from keepalive import keepAlive
config = json.load(open('config/config.json'))
token = config.get('token')
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
bot.load_extension('cogs.greetings')
keepAlive()
bot.run(token)
i dont wnt
There's something about this code I just cant get rightpy @role_group.command(description = "Show the members of the role specified.", usage = "[role]",) async def members(self, ctx, role: discord.Role): members = [f"<@{member.id}>" for member in role.members] if len(members) == 0: no_members = 0 members.append("No members") await ctx.reply(embed = discord.Embed(title = f"{len(no_members)} Members in `{role}`: " if no_members > 0 else f"{len(members)} Members in `{role}`: ", description = f" ".join(members)))when there is no members in the role then I want the title to say 0 members in {role}: but atm it keeps saying 1 members in [role}, supposedly because i'm adding 1 (the string of "no members") to it
U can also use member.mention BTW
Also, u r doing len(no_members) where u should just do no_members
true
@maiden fable :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: object of type 'int' has no len()
It doesn't work...
well at one point I had itpy if len(members) == 0: no_members = len(members) members.append("No members")just changed ti back to this
How come it doesn't raise the error
We already told you. You need to indent your methods
Why declaring multiple variables for same work? Just do py members = [ the list comprehension] or "No members"
And use the members variable directly
cause I hadn't thought of that, thanks for the advice
;
can someone help me, the bot is working locally but not on a remote
can i get help for this error message? It gave me that when i tried to give my bot a status https://hastebin.skyra.pw/botubawoku.sql
yeah that doesn't work, it just gives me this, when I want the bot to say 0 members in {role} when there's no members in the role
you have the role variable there, just use len(role.members) instead of len(members) in the title

oh lol, I have a habit of making things way too complicated
@commands.command()
async def adservers(self, ctx):
if ctx.author.id == 826419463506755605:
activeservers = self.client.guilds
file = open("servers.txt", "r+")
file.truncate(0)
for guild in activeservers:
with open("servers.txt", "a", encoding='utf-8') as f:
f.write(f"\n")
f.write(f"{str(len(guild.members))} | {guild.id} | {guild.name}")
f.close()
await ctx.send(file=discord.File("servers.txt"))
else:
return
I use this command to see what servers my bot is in, but this is the output i get (a lot of "Nones" and the member count is on 0 or 1
so I have this command for showing a roles permissions, is there a better way for me to be formatting it? so instead of checking against my list I just pull the permissions themselves and format thempy @role_group.command(description = "Show the members of the role specified.", usage = "[role]", aliases = ["perms"]) async def permissions(self, ctx, role: discord.Role): has_perm = [perm for perm in self.bot.config.role_perms if getattr(role.permissions, perm)] await ctx.reply(embed = discord.Embed(title = f"Permissions for `{role}`", description = f", ".join(has_perm))) and this is the role_perms listpy role_perms = ["administrator", "manage_guild", "manage_webhooks", "manage_channels", "manage_roles", "manage_emojis", "manage_messages", "manage_nicknames", "view_audit_log", "view_guild_insights", "kick_members", "ban_members", "move_members", "deafen_members", "mute_members", "read_messages", "send_messages", "send_tts_messages", "embed_links", "attach_files", "read_message_history", "add_reactions", "external_emojis", "connect", "speak", "priority_speaker", "use_voice_activation", "stream", "create_instant_invite", "change_nickname", "mention_everyone"]
like this?
import discord
from discord.ext import commands
class Greetings(commands.Cog, name="Greetings"): # We Subclass commands.Cog . if the name kwarg is not passed, the Cog name is taken to be the same as the class name
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener() # just like @bot.event
async def on_member_join(self, member): # called when a member joins
channel = member.guild.system_channel # get the guild's system messages channel - where welcome and boost messages are sent. You can change this to bot.get_channel(channel_id)
if channel is not None:
await channel.send('Welcome {0.mention}.'.format(member))
@commands.command() # this is how you create a command in a Cog. The same as @bot.command()
async def hello(self, ctx, *, member: discord.Member = None): # always remember to pass "self"!
"""Says hello""" # command description
member = member or ctx.author
await ctx.send('Hello {0.name}~'.format(member))
def setup(bot):
bot.add_cog(Greetings(bot)) # register the cog
How to make bot send a message at a specific time? For example 00:00 IST
๐ช ๐โโ๏ธ
so I have this function which helps me fill out embeds nice and easilypy async def timestamps(self, member, embed, avatar): embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True) if avatar == True: embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True) embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True) ordinarily I would call it in my commands as await self.timestamps(member, embed, False) if the command is in the same cog/file, how would i call it from inside of a different cog? Do I need to do```py
from timestamp_function_cog import timestamps
await self.timestamps(member, embed, False)```
im currently making a modlog for my bot, and i need to retrieve the toggle from a mongo collection. to get the toggle from it, i need the guild id. im currently using the on_member_update and similar methods, and they dont seem to have a param from which i can access the guild id. is there any alternative to this?
Fix your indentions, make sure to click on tab
with on_member_update you have a Member object given as parameter, you can get the guild from the member. A Member is member of one guild, the one where he changes something like the nickname or the roles
To indent your code properly
yeah i just figured that out
thanks for the help tho
spaces over tabs
tabs = 4 spaces
Yes, use tabs
Well you should be using spaces
fakenews
Just change your code smh
Tabs should be used solely to remain consistent with code that is already indented with tabs
That's really only in the context of very large code
imagine use spaces, but i put sublime settings tabs == 4spaces
only time i use spaces in python is when trying something fast in python-interpeter
If sublime inserts spaces instead of tabs then you're fine
It's recommend to change your ide/text editors settings to insert spaces instead of tabs
Change it
too lazy to redo all indentations atm ๐
Does black refactor tabs into spaces?
i dont even know what that is
The IDE does that automatically
I doubt all of them do
Well VSC does it
So does pycharm
If you aren't using idle what are you doing with your life
There's a really short way, py [perm for perm in role.permissions if perm[1]]
๐
U better not ask...
I use my terminal
Cool, I thought I was doing it in a rather complicated way
perm variable there is a tuple in form of ( permission , True) so you might like using perm[0] for permission name
๐
i dont use idle, i use afk
...
You guys use computer?
Programming on phone is pain
@final iron i cant do that
Do what
just try help a simple code here on phone is a hell
I'm on mobile right now
u need a laptop bro
one guy on youtube tried program a phoneapp with using phone, he gave up cause started get too much pain in his thumbs n went to a dr
๐
i think he cheated and used keyboard later on to phone
easier said that done lmao
hey
how to send a txt to specified channel
i mean i wanna use logging
and looping like 10min each its sending logs.txt to my channel
hey guys i know absolutely nothing about building bots with python
can anyone help me?
how can i learn python?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
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.
what happened?
I think I have food poisoning
yikes
atleast you can still code
or sit at your computer for an inordinate amount of time
Not at the toilet I can't
you have a point
move the toilet with u
๐
@final ironam pretty sure there are some chinese company doing portable toilet/officechairs
Yeah bro it's called a bucket
๐
toilet/bath is a good moment of philosophy tho about codes or problems u have to fix
I guess
best is when u get stuck n realise u been there for 30min
I'm working on a Twitter API wrapper and I need to figure out how to share the token across files
i have written everything correctly still my bot isn't responding to anything can anyone help
Send ur code we canโt just help like that
also like do you have a error handler ?
no
Then send ur code
how do i send......copy paste?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!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.
import discord
from discord.ext import commands
bot = commands.bot(command_prefix = ".")
@bot.event
async def on_ready():
await bot.change_presence(stat = discord.Status.idle)
print("My ready is body")
@bot .command()
async def ping(ctx):
await ctx.send(bot.latency)
bot.run(token)
Itโs commands.Bot
yes
yes
How much do you know about python? ๐ค
It wonโt work
just a begginer thats y i m asking
Then first learn python
and that's why you shouldn't start with discord.py
ohk thx
you need to know python to use external package, expecially if created by users
ohk i will
yeee
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
btw thx u both
There are some good resources their about learning python check it out
so I'm doingpy has_perm = [perm for perm in role.permissions if perm[0]]and getting this errorpy ERROR:cogs.error_handler:TypeError: sequence item 0: expected str instance, tuple found (In permissions) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 135, in permissions await ctx.reply(embed = discord.Embed(title = f"Permissions for `{role}`", description = f", ".join(has_perm)))i'm not great with tuples
wait what are you tryin to do?
Asked ya to use the first index for the perm ```py
[ perm[0] for perm in .....
oh, I thought you meant use if perm[0], my bad
oof
so I'm still getting the same errorpy has_perm = [perm[0] for perm in role.permissions if perm[1]]
Rip, cannot play FN at 400 ms ;-;
well that's the errorpy ERROR:cogs.error_handler:TypeError: sequence item 0: expected str instance, tuple found (In permissions) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/info.py", line 135, in permissions await ctx.reply(embed = discord.Embed(title = f"Permissions for `{role}`", description = f", ".join(has_perm)))the code i sent before was what I (think) they suggested I chnage my code to for it to work
well you are making a tuple
has_perm[0] ?
oh nah
join takes a tuple
bro idek
what's perm[0] ?
okay this is the full codepy @role_group.command(description = "Show the members of the role specified.", usage = "[role]", aliases = ["perms"]) async def permissions(self, ctx, role: discord.Role): has_perm = [perm for perm in role.permissions if perm[1]] print(has_perm) print() await ctx.reply(embed = discord.Embed(title = f"Permissions for `{role}`", description = f", ".join(has_perm[0])))and this is the print out put of has_perm py [('kick_members', True), ('ban_members', True), ('administrator', True), ('manage_channels', True), ('manage_guild', True), ('add_reactions', True), ('read_messages', True), ('send_messages', True), ('manage_messages', True), ('embed_links', True), ('attach_files', True), ('read_message_history', True), ('mention_everyone', True), ('external_emojis', True), ('connect', True), ('speak', True), ('use_voice_activation', True), ('change_nickname', True), ('manage_nicknames', True), ('manage_roles', True), ('manage_webhooks', True), ('manage_emojis', True), ('use_slash_commands', True), ('request_to_speak', True)]
yeah, this is is a list of tuples
so has_perm[0] is a tuple
you have to add has_perm[0][0]
that's the str
this is what I was doing beforepy role_perms = ['administrator', 'manage_guild', 'manage_webhooks', 'manage_channels', 'manage_roles', 'manage_emojis', 'manage_messages', 'manage_nicknames', 'view_audit_log', 'view_guild_insights', 'kick_members', 'ban_members', 'move_members', 'deafen_members', 'mute_members', 'read_messages', 'send_messages', 'send_tts_messages', 'embed_links', 'attach_files', 'read_message_history', 'add_reactions', 'external_emojis', 'connect', 'speak', 'priority_speaker', 'use_voice_activation', 'stream', 'create_instant_invite', 'change_nickname', 'mention_everyone'] has_perm = [perm for perm in role_perms if getattr(role.permissions, perm)]but hikari lover suggested has_perm = [perm for perm in role.permissions if perm[1]] as a more compact way of doing it
perm[0] for perm in... seems good
What u even tryna do :stare:
Just use the Permissions class
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.update "discord.Permissions.update").
yeah that's not quite what i want, I would like it to show all of the permissions a role has
this was working but it doesn't seem very efficient to me so I was looking for a way to streamline it
I would like it to show all of the permissions a role has
pls help
how to set my bot offline, i accidentally hosted my bot on my pc lmfao
how can i do a temp channel bot ?
I'm not amazing with d.py but I think your looking for ignore that first bit You could also save yourself a variable with activeservers = self.client.guilds() (maybe).py @commands.command() async def adservers(self, ctx): if ctx.author.id == 826419463506755605: file = open("servers.txt", "r+") file.truncate(0) for guild in self.client.guilds: with open("servers.txt", "a", encoding='utf-8') as f: f.write(f"\n") f.write(f"{str(len(guild.members))} | {guild.id} | {guild.name}") f.close() await ctx.send(file=discord.File("servers.txt")) else: return
what are you using to program?
i'm using d.py lib and VSC as ide

๐
Hey can anyone please help me with a bot which fetches an Information of number of active players from an player pannel and display it on the discord in real-time i mean I have started the work on it though
you mean someone joins a vc and a new vc/text channel gets created and they get pulled to that vc(if a new one was made)
did you save and rerun it?
yep, many times just to be sure
try printing py [perm[0] for perm in role.permissions if perm[1]]
yes
okay what the living hell, it's working all of a sudden. I'd saved and reloaded it about 8 times before I made any changes to try to troubleshoot and now it's working out of the blue
great
sorry for wasting your time
I haven't tested this but I think you'd want something like thispy @Cog.listener() async def on_voice_state_update(self, member, before, after): await self.bot.create_text_channel(name = f"{member}'s channel", category = before.category, topic = f"{member} joned {before.channel} so a new channel was created.") await self.bot.create_voice_channel(name = f"{member}'s channel", category = before.category)
create txt docs: https://discordpy.readthedocs.io/en/master/api.html?highlight=create channel#discord.Guild.create_text_channel
create vc docs: https://discordpy.readthedocs.io/en/master/api.html?highlight=create channel#discord.Guild.create_voice_channel
(Apologies if this is perceived as heavy spoon feeding)
is there a way to make the bot send messages only visible to one person ?
bigger bots use it after application commands
How can I create a restart bot command in discord.py?
my current progress:
@commands.command()
async def restart(self):
await ctx.bot.logout()
os.execv(sys.executable, ['python'] + sys.argv)
await ctx.send(f"{self.user} has restarted.")
i think you need to make a script that first runs your bot script as a execution, and then restarts that from within that script
how u gonna make a command reach that i dunno
oh well logout, login? but that dosnt restart script
just the connection?
- maybe u can unload all cogs, logout, log in reload all cogs?
just make a command that reload all cogs if you don't want to reload the bot everytime
!d discord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
You can only do it with interactions, like buttons, selects, slash commands. Not with prefix commands
or DM's!
class disnake.MessageInteraction```
Represents an interaction with a message component.
Current examples are buttons and dropdowns.
New in version 2.1.
DM's are not "visible to one person"
really?
aha
They're just DM hahahaha
!d discord.InteractionMessage.send
No documentation found for the requested symbol.
well its visible to one ๐
I don't think that Discord has Interactions
Okay I;m done
you have to add discord-slash extension
!d disnake.MessageInteraction.send
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
If the interaction hasnโt been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_message()`](https://docs.disnake.dev/en/latest/api.html#disnake.MessageInteraction.original_message "disnake.MessageInteraction.original_message") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if youโre sending a followup message.
class disnake.ApplicationCommandInteraction```
Represents an interaction with an application command.
Current examples are slash commands, user commands and message commands.
New in version 2.1.
how do i get the cog class name from the cog object?
as a string
every class has a __name__ property
how to decrypt files encrypted with pytransorm
you're in #discord-bots where you would want to ask about things related to discord bots
What does this have to do with discord bots
encrypting uids

man i hate slash commands, because sometimes as a user the list of commands from all bots is not even displayed just the built-in ffs
thanks 
maybe the channel has slash commands specifically disabled
or just discord being discord i suppose
ive been stuck on this problem for days.
I'm making blackjack for discord. using pycord. With this being said /blackjack starts the game but how can I allow people to hit? I want people to be able to hit if they just say "hit"
you might want to use buttons for that
i need to decrypt file of a bot i think there is a grabber in it so i need to check
yeah ihate buttons
theyre a pain
cant I just check if someone say "hit" within the slash command?
or just hit
the message content would just be hit?
yeah
i would not want to waste my time on something that wont work after the big update discord is going to release, making message intent privileged
you need message intent to see messages
that isn't dmed to your bot or doesnt have your bot mentioned in it
makes no sense because sometimes works and sometimes not lmao
and + it's even my server and i know i didn't disabled anything kek
ima off myself now
discord will most likely reject your request for the intent because it can be implemented using buttons, select menus or slash commands
i dont wanna learn how to use buttons properly its so hardd
is it possible to make a like subcommand for blackjack?
using buttons is easier with discord.py 2.0 buttons than anything else you are trying to do
discord 2.0 wym by that
you will eventually get used to it
idk im a noob coder in general
discord.py's version 2.0
Ew pycord
a fork of discord.py
Then you're probably on the 2.0 version
pycord is good besides some of their staff members
that actually sucks
some of their staff members do be rude as fuck
No it's not
makes me so sad with the message intents, LIKE I JUST figured out how to do it
what you should care about is how good is the library not staff
Even danny specifically called them out
really
did he?
why did he call them out what he say
Yes
imma go bravo six and search
He was just talking about how he didn't like most forks and he mentioned that pycord specifically was his least favorite
ah
anyone got a good video they can recommend for pycord buttons cause i guess ima have to figure out buttons :/
It's the same as discord.py's buttons, since pycord is just a fork
oh never knew discord.py had buttons tbf
It does
about pycord 
Hi people!
ngl i'm pretty glad i decided to rewrite the bot with disnake
I'm trying to make a bot join a server but every time I use the link, it just says no scopes were provided
I'm using diskord atm
Do I need to specify the scopes in the script for the bot directly or something like that as well?
you need to specify the scopes from developer portal
before generating the link you need the scopes and permissions
right, when generating the link, i did that
since im using buttons inside of a command what would i do for the @CLIENT part?
when i use the link it shows me the bot and allows me to choose the server and get through the captcha, then says no scopes were provided
or do I even need anything regarding client?
you have to provide it a scope, in your case, Bot
wdym
for example I do
@CLIENT.slash_command(guild_ids=[938836203275452436], name = "blackjack", description = "Command is in testing.")
async def blackjack(ctx):``` to start blackjack, whenever i do async def buttons inside of this command do I need another @client if so what would i add
yes, did that! and added permissions to view message history and such
whats the url? you may censor the bot user id if you want
1 sec, was just about to make the screenshot
!paste can be used aswell
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.
how would I make a button send on the message containing the embed of the player / dealer cards
How would I make a command to ban someone that isn't in the server
use Guild.ban
!d discord.Guild.ban
!d discord.Guild.ban
Bot dead
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
so wait, before i embarrass myself further, what am I supposed to put in the redirect URL? I need it in order to generate the scopes URL
message intents only applies to servers above 100 right?>
Can a bot see: for how long user has been in a voice chat?
yes, its only for verified bots
no
but you can cache the user's join time with the event
From what I've read so far, i thought I had to craft an https://discordapp.com/oauth2/authorize?&client_id=[CLIENTID]&scope=bot type URL for the redirect, and then use the URL generation, but is this wrong?
on the dev page?
I do have a server I can use if need be
https://discordapi.com/permissions.html use this to make a url
A small calculator that generates Discord OAuth invite links
yes
the client id is your bot's id
Ty
maybe I'm not understanding something more basic? So, I have this bot that was created in one account and another account which has management rights on the server has tester access to the bot. I thought the link simply allows me to invite the bot directly to the server from the acc that has manage rights, with the appropriate scopes and permissions selected in the dev portal (I ticked "bot" and some permissions to read history and create private threads)
Now copy that link and open it with the account that has those permissions
@minor totemmust be bluenix i nvr seen u respawn before. Hi.
From what I remember no, you'll need to keep track of when the user joined and when they leave.
๐
when i run this https://github.com/ChristopheCVB/VoiceCreateBot
What happens when you run that?
i get this error
None
Traceback (most recent call last):
File "C:\Users\L3\Desktop\VoiceCreateBot\voicecreate.py", line 37, in <module>
bot.run(DISCORD_TOKEN)
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 663, in run
return future.result()
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 642, in runner
await self.start(*args, **kwargs)
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 605, in start
await self.login(token)
File "C:\Users\L3\Python\lib\site-packages\discord\client.py", line 473, in login
data = await self.http.static_login(token.strip())
AttributeError: 'NoneType' object has no attribute 'strip'
You need to set the correct environment variable, see how None is printed? That means that the environment variable couldn't be defined.
4.Open voicecreate.py in a text editor and replace 'Enter Discord Token here' with your bots token
did this?
yes
Since None is printed I have reason to think otherwise. Are you sure?
ah they have it wrong in the readme. did you create an .env file?
how
if not, make an .env file , with this structure ```
DISCORD_TOKEN_VOICE_CHANNELS= 'your token'
Those need to be loaded by some form of env package, which this module doesn't do
What OS are you on?
win
works for me without loading, but yea it should be
voicecreate.py line 17
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN_VOICE_CHANNELS")```
how would i mention a user in a hyper link?
they use .getenv directly
and pls dont use that ffs @pliant nacelle
ffs ?
voicecreate.py lines 12 to 16
client = discord.Client()
bot = commands.Bot(command_prefix=".")
bot.remove_command("help")```
is how you make a hyper link if you want to mention im not quite sure
this makes me hate it already
oh gosh
what is that
obviously... But @gusty hatch doesn't work
Before you run the bot you have to do set DISCORD_TOKEN_VOICE_CHANNELS = ... and replace ... with your actual token.
Like a DM to them?
already did it
this whole conversation is giving me a stroke
Because they instantiate a client and then do nothing with it?
they initiate a client , then a bot
whats the point of doing that?
Blu what am i doing wrong 
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
this is all they used, the client definition was useless
just making a parent class instance and a child class lol
the Bot class is the subclass of Client so why use both?
it inherits everything
I don't remember if you can do that, because you'll need the DM channel ID but you only have the user ID. Have you tried https://discord.com/channels/@me/344404945359077377
Does that bring you to my DMs?
soo what should i do abt that
no
No idea, they don't use client either - could probably have been accidentally been left over. The code works so why would you notice an issue if you're the person who wrote the code?
when i click it , it doesnt nothing blu
Did that take you to my DMs?
^^^
i already did it
You probably didn't do that correctly if it stil prints None? Try again, and make sure to do it in the same window and place as you later use to run the bot.
yea thats ignore-able , but the env thing ( dot_env library ) we talked about is still not implemented so it "may" not get the env
another thing is, it uses sqlite3 which is blocking
!pip aiosqlite there's already an async driver for sqlite3 could have used that
Yeah then I am not sure, sorry. Usually you'd ping someone and then say "DM @minor totem"
how to edit a embed the bot sent using pycord?
get the msg and edit it
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
i regenerated the token and replace it
still the same None
I used to complain about this too, and I really still do it it comes up in code I am reviewing - but it doesn't matter all that much for a Discord bot that doesn't handle much. You'll block the event loop for a miniscule amount of time.
If this is what Malphas is looking for it probably doesn't matter all that much unless you have an alternative?
would this not work?
em = discord.Embed(title = f"Hand", color = discord.Color.blue())
em.add_field(name = "Player Cards",value = f'{playerHand} | {score1}')
em.add_field(name = "Dealer Cards",value = f'{dealerHand} | {score}')
msg = await ctx.respond(embed = em)```
```py
em2 = discord.Embed(title = f"Hand", color = discord.Color.blue())
em2.add_field(name = "Player Cards",value = f'{playerHand} | {score1}')
em2.add_field(name = "Dealer Cards",value = f'{dealerHand} | {score}')
await asyncio.sleep(1)
await msg.edit(embed = em2)```
idk what im doing wrong tbh but i get an error
the heck is respond
it makes the bot respond instead of send a message
literally what you just did you replied aka responded to my msg
How do you run the bot? What you should do is:
- Open CMD in the directory of the bot
- Set the environment variable (see above)
- Run the bot with like the command line with
pythonorpy
Is that what you're doing?
nope
If you have an error just send it
I can't get it to work
File "C:\Users\Alex\github\Gambling-bot\gamblingbot.py", line 145, in on_message
await msg.edit(embed = em2)
AttributeError: 'Interaction' object has no attribute 'edit'
ahhhhhhh
youre using interactions
how can i set the env
!d disnake.Interaction.edit_original_message
await edit_original_message(*, content=..., embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original, previously sent interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionMessage.edit "disnake.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Note
If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the messageโs attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).
I showed you up here but you said you already did that ^^
Try again
and odd to see you here bluenix how are you
I am alright ๐
good to hearโค๏ธ
as string ?
ephemerals are just a response to an interaction
some shit like that
Is there an error?
It says the member cannot be found
Are you asking whether to use quotes? Since there is no space in a Discord token it doesn't matter.
d.py 2.0 has it
and dislash is a 3rd party lib if you're looking for it
but thats just procastination
and isnt advised
well I'm all about procastination and don't intend to update to d.py 2.0 since my bots only for one server. Once I get around to making a multi server bot then I'll move over to hikari
as if
okey
in the .env should i past bot token ?
or voice channel token
yo would I apply past overwrites into a new one? e.g. keep an overwrite I just made (add a member to a channel) while adding a new member to it
{<Role id=915357451484790916 name='@everyone'>: <discord.permissions.PermissionOverwrite object at 0x0000024316F33B50>, <Member id=351090362682572802 name='Creepy' discriminator='8705' bot=False nick=None guild=<Guild id=915357451484790916 name='Cosmic Overground (Private)' shard_id=None chunked=True member_count=13>>: <discord.permissions.PermissionOverwrite object at 0x0000024316F33A60>} Old overwrite, I wanna add another member to the channel, how would I do this without removing this overwrite
That bot doesn't support .env files
env.py ?
i hate overwrites ๐ญ
You need to use the command I sent above
you didn't send any cmd
I sent this ^^
oh is this a cmd ?
should paste the bot token ?
Not in here, but after that yes.
in place of ...
Yes
i did the cmd ?
should i run now python voicecreate.py ?
Yes now start the script with like python voicecreate.py or py voicecreate.py
Yes
same error
Replace voicecreate.py with this instead: ```python
import discord
import math
import asyncio
import aiohttp
import json
from discord.ext import commands
from random import randint
import traceback
import sqlite3
import sys
import os
client = discord.Client()
bot = commands.Bot(command_prefix=".")
bot.remove_command("help")
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN_VOICE_CHANNELS")
if DISCORD_TOKEN is None:
DISCORD_TOKEN = input('Enter Discord Token: ')
initial_extensions = ['cogs.vc']
if name == 'main':
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
bot.run(DISCORD_TOKEN)
I added that input(). You could open an issue on the repository asking them to make it easier to use in the future
should replace smthng here to my bot token
No, when you run the code it will ask for your token so just paste it and press Enter.
actually idk how to thank you 
i appreciate that
why
if DISCORD_TOKEN is None:
and not
if not DISCORD_TOKEN:
Oh Blue here ๐
Because DISCORD_TOKEN can be a string, and out of habit I explicitly test if it is None since an empty string is also not DISCORD_TOKEN
Yess... I am ๐ค
Good to see you here ๐ค
yeah i have the same habit no worries
an error is displayed, but the text is sent that the user has kicked, how to fix it?
Send the message after kicking them
Though that won't work if that's the only mutual server with them, it won't DM them
@minor totem I'm trying to make sure that when kicking myself, the kick text is not displayed, but only an error
it is for me?
@lapis meadow you can just use len() on bot.guilds
To any discord.py bot dev I have a question. I have a bot that I know is in some servers but I was wondering if I can get a command so that the bot displays in an embed how many active guilds it inor get the bot to update the status of how many guilds its in
.
No, in your code
Check that before, instead of catching the exception that occurs?
Iโm fairly new. Any way someone could provide an example
What are you looking to do? Just say "playing in XYZ guilds"?
Yeah
Do you have a client or bot? There should be .guilds on it that is a list of all guilds. So you can just wrap that in len(...) and that will get you the number your bot is in.
Yes, now put that in like a command, or some form of task that loops every once in a while (maybe each hour?)
30 min i think is enough
How?
๐ค
You'll want it to display somehow as well, so use ctx.send() somehow or bot.change_presence()
@client.command()
async def servers(ctx):
servers = list(client.guilds)
await ctx.send(fโActive in len(servers) servers!โ)
Like this?
Iโm really new at this I apologize
You have an ID right? Do something like if ctx.author.id == the_target_id: and after it put the code you want to run when the author is trying to kick itself and then return so that the rest of the code doesn't run.
No need to apologize, hold on
It should look like this, you were pretty close: ```python
@client.command()
async def servers(ctx):
servers = list(client.guilds)
await ctx.send(f"Active in {servers} servers!")
Note that your quotes were wrong, are you on mobile? They need to be the normal quotes you get on a keyboard
!charinfo โโ
\u201d : RIGHT DOUBLE QUOTATION MARK - โ
\u201d : RIGHT DOUBLE QUOTATION MARK - โ
\u201d\u201d
!charinfo "
\u0022 : QUOTATION MARK - "
the_target_id?
Do you see the difference @lapis meadow?
Okay
Yeah Iโm on my phone at the moment.
Yes, also thanks for all the help! Youโre a literal life saver 
At school until 3 than I can edit the code when I get home.
Replace that with wherever you have the ID of the person you're kicking, that may be target.id or like member.id depending on how theยดcommand is setup
that lovely blue heart bluenix gives it gives me memories
can you tell me how to create a temp channel with that code ?
I have never seen that project before, I don't know.
hi, how to delete bot reply for user msg
everyone tell me that code is bad
Keep the message around and delete it when you want to. ```python
msg = await ctx.send(...)
Maybe put some other code here, like sleeping?
...
await msg.delete()
hello, im trying to set up an avatar command(like /avatar [user] and it sends you the user's avatar) but its not working, heres my code:
I mean reply
So I have this function counting a guilds emoji's```py
emoji_stats = Counter()
for emoji in guild.emojis:
if emoji.animated:
emoji_stats['animated'] += 1
emoji_stats['animated_disabled'] += not emoji.available
else:
emoji_stats['regular'] += 1
emoji_stats['disabled'] += not emoji.available
fmt = f'Regular: {emoji_stats["regular"]}/{guild.emoji_limit} | Animated: {emoji_stats["animated"]}/{guild.emoji_limit}'\
if emoji_stats['disabled'] or emoji_stats['animated_disabled']:
fmt = f'{fmt} Disabled: {emoji_stats["disabled"]} regular, {emoji_stats["animated_disabled"]} animated\n'
fmt = f'{fmt} | Total Emojis: {len(guild.emojis)}/{guild.emoji_limit*2}'```and I'm calling it here```py
embed.add_field(name = "Emotes", value = await self.emoji_counter(guild), inline = False)```which I assume is the wrong thing to do since it's showing `None` inside of my embed
That works the same way
What's wrong?
the command does not work
@minor totem I do not understand(
it shows up on the slash commands list but i not send it
"str" has no attribute "url"
It doesn't look like you return anything, you need to add return emoji_stats at the end
no, Can the original user msg find the bot reply?
I want to find the bot relpy at the original user msg
If you send the code you have for the command I can give you some more specific help
could you please send the whole error?
sure
is there a way?
That's not how your code looks like. Have you saved?
Are you trying to reply to a deleted message?
yes, or edit
You can't reply to a deleted message, when it is deleted it is gone.
edit?
You cannot edit a deleted message either - it has been deleted.
yes, many times
okay i added the return, do I need to f-string any of my code somewhere bc it used to look the first pic but now it looks like the second
no, i mean i want to find the existence of bot reply in user's msg
Yeah now you have the Counter, so you want to sum all the values?
not after removal
You have a user message and want to find the message that the bot sent in reply?
yes!!
That is impossible, you can only do the opposite (get the original message from a bot reply).
the reference ?
you have to save the message when sending it
Am I able to display this in an embed? It would be like this ( b=discord.Embed(titleโServer count!โ, description = โWorking inside of {servers} servers!โ, color = 0x00ff00)
await ctx.send(embed=b)
so how fix?
Can we see the code?
i sent it already
oh
Send it again
@final iron
you have to convert user to a discord.User
Type hint user to discord.User
Yes, a bot reply has a reference to the original message. If you have the original message there is no reference to the reply though
or Member
user = discord.User?
no, user: discord.User
No
returning fmt instead of emoji_stats fixed it
You need to type hint it
?
That looks correct. Just make it a f-string like this:f"Working inside of {servers} servers!"
a: int
hint it? what that
My apologies thanks!
Type hinting a to an int
Ah I see, that was the intended return type. Nice!
!resources should hide here somewhere
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
typehint
@minor totem
Is this interactions.py?
hmm?
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason="ะััััััะฒัะตั"):
try:
if member==ctx.author:
emb=discord.Embed(title="โ Error", description="ะั ะฝะต ะผะพะถะตัะต ะบะธะบะฝััั ัะตะฑั!", color=discord.Color.from_rgb(0, 0, 255), timestamp=ctx.message.created_at)
emb.set_footer(text="ยฉ ะัะต ะฟัะฐะฒะฐ ะทะฐัะธัะตะฝั The Greatest", icon_url=ctx.author.avatar_url)
await ctx.reply(embed=emb)
else:
await member.kick(reason=reason)
emb=discord.Embed(title="ะะธะบ ะฟะพะปัะทะพะฒะฐัะตะปั", description="**__ะะฝัะพัะผะฐัะธั:__**", color=discord.Color.from_rgb(0, 0, 255), timestamp=ctx.message.created_at)
emb.set_footer(text="ยฉ ะัะต ะฟัะฐะฒะฐ ะทะฐัะธัะตะฝั The Greatest", icon_url=ctx.author.avatar_url)
emb.add_field(name="**ะฃัะฐััะฝะธะบ:**", value=f"**{member.name}** ({member.mention})", inline=False)
emb.add_field(name="**ID:**", value=f"**{member.id}**", inline=False)
emb.add_field(name="**ะะธะบะฝัะป:**", value=f"**{ctx.author.name}**", inline=False)
emb.add_field(name="**ะัะธัะธะฝะฐ:**", value=f"{reason}", inline=False)
await ctx.reply(embed=emb)
except Exception as e:
await ctx.send("I can't do that")
print(e)
Yes?
What library is this that has slash command support
ayt
Yes, this is great! Just add return after await ctx.reply(embed=emb) so that it looks like this: ```python
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason="ะััััััะฒัะตั"):
try:
if member==ctx.author:
emb=discord.Embed(title="โ Error", description="ะั ะฝะต ะผะพะถะตัะต ะบะธะบะฝััั ัะตะฑั!", color=discord.Color.from_rgb(0, 0, 255), timestamp=ctx.message.created_at)
emb.set_footer(text="ยฉ ะัะต ะฟัะฐะฒะฐ ะทะฐัะธัะตะฝั The Greatest", icon_url=ctx.author.avatar_url)
await ctx.reply(embed=emb)
return
else:
await member.kick(reason=reason)
emb=discord.Embed(title="ะะธะบ ะฟะพะปัะทะพะฒะฐัะตะปั", description="ะะฝัะพัะผะฐัะธั:", color=discord.Color.from_rgb(0, 0, 255), timestamp=ctx.message.created_at)
emb.set_footer(text="ยฉ ะัะต ะฟัะฐะฒะฐ ะทะฐัะธัะตะฝั The Greatest", icon_url=ctx.author.avatar_url)
emb.add_field(name="ะฃัะฐััะฝะธะบ:", value=f"{member.name} ({member.mention})", inline=False)
emb.add_field(name="ID:", value=f"{member.id}", inline=False)
emb.add_field(name="ะะธะบะฝัะป:", value=f"{ctx.author.name}", inline=False)
emb.add_field(name="ะัะธัะธะฝะฐ:", value=f"{reason}", inline=False)
await ctx.reply(embed=emb)
except Exception as e:
await ctx.send("I can't do that")
print(e)
im using python
jesus
from discord_slash import SlashCommand
what?
is there some better thing to be using on replit?
Ok
If you don't want to help just leave
I do... sorry
thank you he is getting on my nerves a bit
its fine
Ah look, the library you are using is discord_slash. Let me look up the documentation
ok thx
i didnt know what you meant by library, i dont usually have to ask questions about this kinda thing so im not at the top of my game exactly
Ah, hmm, this is interactions.py (a lot of renaming). Which version do you have installed? Can you run like pip freeze and find discord-py-slash-command?
To be clear @kind path this was directed towards you ^^
ik
how about i just look at my installed packages instead?
3.0.3
does that help?
Yes thank you
yw
Thank you @minor totem
@kind path found it! Here's an example of a user-option: ```python
@slash.slash(
name = "user",
description = "user",
options = [
create_option(
name = "user",
description = "user",
required = True,
option_type = 6
)
]
)
async def user(ctx, user: discord.User):
print(user)
await ctx.send("Done")
How to check if bot is 'speaking'
like in voice channel?
idk how that works
I tried ^^ but it doesnt work
i tried learning that stuff a while back and gave up
You want to know if your bot is speaking?
playing music, yes
!d discord.Guild.voice_client
property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
I'm not sure if VoiceProtocol has everything that VoiceClient does
I donโt think there is something to check that
well clearly, VoiceClient.is_playing does exist
Mhmm
I canโt find the right channel for this so anyone know how to get requests from website with headers
By the looks of it, what you need to do is keep the VoiceClient around when you connect to the voice channel. So you'll need need to store it on the bot somewhere!
no, but VoiceClient inherits VoiceProtocol ๐ฆ
I tried if ctx.guild.voice_client.is_playing():
oh right
what do i import exactly? like how spell
as Bluenix said, save the VoiceClient when connecting to the voice channel
how
there used to be if ctx.guild.voice_client.is_playing()
I see
@slash_util.slash_command(description = 'Joins the voice channel')
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.guild.voice_client:
return await ctx.send("I am already connected to a voicechannel.")
vc = await ctx.author.voice.channel.connect()
await ctx.guild.change_voice_state(channel = ctx.author.voice.channel,self_deaf=True)
await ctx.send('I joined the voice channel!', ephemeral = True)```
yeah
So you have from discord_slash import ... with ... being some things like SlashCommand yeah? Just add create_option() to that.
vc is your VoiceClient
not work
Make sure to keep vc around. If you keep a dictionary on the bot you can do like ctx.bot.my_voice_clients[ctx.guild.id] = vc.
Why not?
yh I see
its not about if the bot is connected or not btw
its about if its playing
"cannot import name "create_option" from "discord_slash"
Yeah, so then you can access the dictionary later like this: ```python
vc = ctx.bot.my_voice_clients.get(ctx.guild.id)
if vc is None:
# The bot isn't connected. Tell the user this
...
return
You can now do something with 'vc'
print(vc.is_playing())
Aaahhh, sorry, hold on.
yeah
That's what the code I showed allows you to see
I see
Okay I found it, what you need to do is import manage_commands and then do manage_commands.create_option
manage_commands was already imported
Great, then change create_option to manage_commands.create_option
ok
ok, the code will run now(thats a good thing) but the command wont work
What do you mean? Why not?
@minor totem Can you tell me how to make it so that when a user does not have a role for a kick, it says that there are no rights?
no title, nor description
Is there some sort of Event reference when user connects with voice channel?
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
thanke
there is no print
it does not do anything
i ran command twice and it printed nothing
You can use this: https://discordpy.readthedocs.io/en/master/api.html#discord.Member.guild_permissions
So you'd do like ctx.author.guild_permissions.kick_members
Where do you print? Make sure to print before you get the error
Okay
@slash.slash(
name = "user",
description = "user",
options = [
manage_commands.create_option(
name = "user",
description = "user",
required = True,
option_type = 6
)
]
)
async def test(ctx: SlashContext, user: discord.User):
embed=discord.Embed(description="** **", color=0xffc700)
embed.set_image(f"{user.avatar_url}")
print(user)
await ctx.send(embed=embed)
Yeah look, the error happens at embed.set_image(f"{user.avatar_url}") but the print is on the line below it.
actually, i have to go for a while, ill try and figure the rest out later, but i gtg, thx for the help tho
ctx.guild.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(
executable=f"C:/Users/bert/OneDrive - DvM Humaniora/Documenten/ShareX/Tools/ffmpeg.exe", source=url)),
after=lambda error: self.bot.loop.create_task(self.play_next_song(ctx)))```
whenever I click "create application" the website just diverts me to the discord home page. How do I avoid this
nevermind, I figured it out
use a proper library please
just watching that it hurts
I
the PEP8 please


