#discord-bots
1 messages ¡ Page 471 of 1
give the code and traceback
Lol
How do you send embeds in discord.py?
Whats in music_bot?
.send(embed=your embed)
i think its the cog class
yay my fun facts bot is basically g-2-g đ
g2g?
yes, the embed field
Good to go, ig?
it didnt show up, even tho i have the perms 
show ur code
perms = []
full_perms = member.guild_permissions
key_perms = {
'administrator': 'Adminstrator',
'ban_members': 'Ban Members',
'kick_members': 'Kick Members',
'manage_guild': 'Manage Server',
'manage_channels': 'Manage Channels',
'view_audit_log': 'View Audits',
'manage_messages': 'Manage Messages',
'manage_nicknames': 'Manage Nicknames',
'manage_roles': 'Manage Roles',
'manage_permissions': 'Manage Permissions',
'manage_webhooks': 'Manage Webhooks',
'manage_emojis': 'Manage Emojis',
'mention_everyone': 'Mention Everyone',
'deafen_members': 'Deafen Members',
'mute_members': 'Mute Members',
'move_members': 'Move Members',
}
for permissions, user_perms in key_perms.items():
if user_perms is True:
perms.append(user_perms)
if perms:
em.add_field(name='Key Permissions', value=', '.join(permissions), inline=False)
key_permsneeds to be removed. and itsin full_permspermissionsis what needs to be appended
you donât need a dict you could just get the name of the permission, strip _ from it and call title on it
actually replace _ with a space
i think this is easier?
your method is not easier
this is what i did for server features
full_perms.items()?
yes
no, just full_perms
ok so should i change key_perms to what blanket said?
"perm" is the permission as a string. so u need to add the "perm" to a list
key_perms needs to be removed entirely. its not needed
my vars are different..
so change them accordingly...
is this needed
perms = []
yeah. thats where the string representation of the permissions will be stored
perms = []
full_perms = member.guild_permissions
for permissions, value in full_perms:
if value is True:
perms.append(permissions)
exactly. that should work
then ull have to use str.title() like blanket said and remove the _
wtf lmfao
lmao. whatever u did...is not right 
perms = []
full_perms = member.guild_permissions
for permissions, value in full_perms:
if value is True:
perms.append(permissions)
if perms:
em.add_field(name='Key Permissions', value=', '.join(permissions), inline=False)
Why are you not joining perms?
oop
yeah. wrong variable
works now.. but there are some unwanted perms i want to remove... thats why i did the whole key_perms thing
Make a list of the permissions you want and use getattr
can i msg you
you still didnât replace nor title the string
Rather not
make another if statement check (or combine it). copy and paste the "keys" from that key_terms dict into a tuple and check if the current permission is in the tuple
how to i show you idk i can sell all to here
How do you make your discord bot know when you've reacted to a message?
on_reaction_add
someone help me in #help-pineapple
Your hosting using your own html website?
wdym?
i am trying to make it accept responce from everyone
everyone from what a website?
perms.append(permissions.replace('_', ' ').title()
That will fix your problem
import discord
from discord.ext import commands
class Gunsmith(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def gunsmith(ctx, gun : str = None):
if gun == None:
await ctx.send(f"Please mention a gun, {ctx.author.mention}!")
if gun == "kn44":
embed = discord.Embed(
title = ("KN44 GUNSMITH"),
description = ("KN44"),
colour = discord.Color.blue())
embed.set_footer(text= "Gunsmith Credit : BLOOD OK#0588"),
embed.set_thumbnail(url="https://pasteboard.co/Kiqk3UW.png")
embed.set_image(url="https://media.discordapp.net/attachments/879390150227025921/882461739051012186/image0.png?width=904&height=678")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Gunsmith(bot))```
Where hv i gone wrong in intendation.
Why do u have a comma after set_footer()?
Ah hey there NotBugcat haha
how to make a eval command
i wanted to make a command if i use ?eval ctx.send("hi") the bot should send hi
hey hi
you helped me a lot yesterday thanks for that :)
eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.
!d exec
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3.10/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code thatâs executed is expected to be valid as file input (see the section âFile inputâ in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3.10/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3.10/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3.10/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3.10/library/functions.html#exec "exec") function. The return value is `None`.
@client.command(name='eval')
async def eval(ctx, *, arg:str):
result = exec(arg)
await ctx.send(result)
I have tried this but i am getting this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
aahh ok
and contextlib.redirect_stdout and io.StringIO
Ah u saying that so that the code is evaluated in the physical console?
And not a virtual one?
cz I don't use those
yeah, print("test") will print it in the stdout, but you can use StringIO and make it act like a virtual stdout
hmm
cool. I don't think I am using those as of now tbh
anyone know how to integrate twitch api to announce on discord when someone goes live?
!e ```py
import io
import contextlib
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
exec("print('test')")
print(f"Values printed: {stdout.getvalue()}")```
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
Values printed: test
Hmm cool
i did remove it, but that still didnt help
@lament mesa i am getting this error
discord.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '"', in non-quoted string```
@client.command()
async def evalo(self, ctx, *, body: str):
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
exec("body")
print("Eval runned: {stdout.getvalue()}")
i am pretty new to this eval thing đ
import discord
from discord.ext import commands
class Gunsmith(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def gunsmith(ctx, gun : str = None):
if gun == None:
await ctx.send(f"Please mention a gun, {ctx.author.mention}!")
if gun == "kn44":
embed = discord.Embed(
title = ("KN44 GUNSMITH"),
description = ("KN44"),
colour = discord.Color.blue())
embed.set_footer(text= "Gunsmith Credit : BLOOD OK#0588"),
embed.set_thumbnail(url="https://pasteboard.co/Kiqk3UW.png")
embed.set_image(url="https://media.discordapp.net/attachments/879390150227025921/882461739051012186/image0.png?width=904&height=678")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Gunsmith(bot))```
Where hv i gone wrong in intendation.
ohh..
i removed it from my actual code and it still doesnt work
imagine using bot
?evalo ctx.send("hi")
why is there self in the command args
that wont work because ctx.send is a corotine
hey guys i is anyone has a bot info code?
it needs to be awaited
umm so how to run the command?
hey hi i figured it out
but how to many the eval work with multiline code?
sorry i dont know
oh ok np
naming conventions please
client.command shouldn't be able to exist according to naming conventions
since discord.Client.command doesn't exist
commands.Bot.command exists, and commands.Bot should be named 'bot' for the instance
naming conventions are very important
client = commands.Bot
exactly
client = implies you use discord.Client
you use commands.Bot
according to correct naming you should be doing bot = commands.Bot
#GRAPH
def graph(formula, x_range,plot='normal'):
fig, ax = plt.subplots()
x = np.array(x_range)
y = eval(formula)
if plot =='normal':
ax.plot(x, y,label=f'y = {formula}')
ax.legend()
ax.grid()
fig.savefig('figure.png')
def graphIt(x=100,formula='x**3'):
graphing_calc(formula.replace(" ","").replace("^","**").replace('y','x'),np.linspace(-x,x))
# class study(commands.Cog):
@client.command()
async def graph(self,ctx,*,args):
file = discord.File("figure.png")
if 'range' in args:
arg=args.split('range')
print(arg)
graphIt(formula=arg[0],x=int(arg[1]))
else:
graphIt(formula=args)
e = discord.Embed()
e.set_image(url="attachment://figure.png")
await ctx.send(file=file,embed=e)```can someone poitn out the error
what is the error?
You can also name it to client it doesn't really matter
indentation
it does
!pep 8
It does?
pep 8
uhh i dont think i understood whatever you said
also get any random bit of code. doesn't have to be a discord bot. Name EVERY variable Xn with n being a random number
and then wait until you get a bug
good luck debugging that
ok
this is the same principle with client/bot
What bug exactly
you did client = commands.Bot
but there's PEP 8 saying to follow correct naming convention
you did NOT follow correct naming conventions
client = discord.Client
bot = commands.Bot
that's correct naming
oh ok
!d discord.on_guild_remove
discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").
This happens through, but not limited to, these circumstances...
I have a problem with music bot:
@commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send('Paused')
This command works, it pauses the audio but it won't send the message.
I see this in console: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression
dont await it
How do you put a delay after a command so the command cant be spammed, is it not just await asyncio.sleep(5) at the last line of the command?
discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") and the local error handler.
A command can only have a single cooldown.
thats for me?
yes
oh okay XD thanks
what does the NoneType mean tho, just so I know
its the type of None
but why does asyncio not work in this case?
!e ```py
print(type(None))
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
<class 'NoneType'>
can we check if the bot was kicked/left/banned for a guild?
dont think so
audit log? 
or wait
from the guild i am not in but my bot was kicked
it's the bot
!d discord.AuditLogAction.ban
!d discord.AuditLogAction
class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
nah the bot left the server so he can't check audit log anymore
what?
Oh sorry I thought he meant the audit log actions
huh
not working whaiii??
on_guild_remove exists?
anyone
How can my bot send automatic messages every 10 minutes? Python
bro reminder command
common
bro i kinda suck at coding
make it
its ok search reminder command and watch on youtube
help meeeeeeee
its not working
use tasks
Why copy code
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
bro i watch youtube and then copy ok
typehint member ig?
so i learn and then
that aint learning
bro sometimes it work other times it dont work
member wouldn't work, cause the member is banned already
user would definitely works
I mean
Use 4 spaces for indents
whay
ohk
defining member_name, member_discriminator like that is bad
ohk then how do i do it
just use member.name and member.discriminator, or you can just do if user.id == member.id
i mean, if the user's name was test#something#8377 then it will raise an error or not work as expected
where
to discriminator
or name??
!e ```py
user = "test#test#8377"
user_name, user_discriminator = user.split("#")
print(user_name, user_discriminator)
@high flame :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | ValueError: too many values to unpack (expected 2)
?
can one bot delete the msg of other bot , if yes then how?
yeah, you just need manage_messages perm and the discord.Message instance
and then delete it like you do to a user message
something is None, and i have a good feeling it's voice_client
Like the bot isn't in a voice channel when using the command
What is this?? :\
Read da error
which one
wat
means? all are long?
no wait
i have changed it to len()
yes len returns the amount of things in a list or a dict etc
in an iterable*
i ask the bot for joining my voice channel, but the conssole say this. i add import PyNaCl but they say that there isnt any module named PyNaCl. I am using repl.it. what should i do now>
yee thanks
and you dont have to import it
because repl sucks.
because it's replit and you should NEVER use replit
Why my if isn't work when letter is big?
because you're comparing it to a list of lowercase words
and python is case sensitive
so you need to make your word you want to check also lowercase
yee. i tried Print("Python") but nothing work.
how can i do to make it case insensitive
nah
read my messages
!d str.lower
str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3.10/library/stdtypes.html#id15) converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
hm
Does anyone know why it fails opening the JSON file? it prints "Could not load amounts.json" but I have made a json file named to "amounts.json" in the same place as the code it self but it still doesn't find it.
@bot.event
async def on_ready():
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
could not open could mean anything
can you help me how i should do it in code? Sorry im still beginner
or in this case it 's your own error
message.content.lower()
if you're this much of a beginner i have my questions why you decided to do discord.py
dpy is extremely complex
show your file directory
a screenshot
yeah I know that but the error is if the script doesnt find the json file and that is what I am ocnfused about. I dont understand how the script doesnt find the file when I feel like I did everything right
not working, still when word have 1 big letter if is not true
show new code
try "code/amounts.json"
could you remove the try except and just let it print a traceback?
so i can see exactly what it's doing?
should work, have you restart it?
what db is the best for discord bots? mongodb, or mysql?
idk, i prefer mysql
i'd say postgresql
in the end it's just personal preference tho
postgres is one of the most popular ones, followed by mysql and mongo
but it's what you want
postgresql is too complex for a simple bot
what about storage tho?
for big bots it's worth it actually
bruh, that worked
every db that exists can hold like trillions of data
oh thats nice then
nice
thx!
mongo is nosql
yeah, but for a big company like Google probably nah
so maybe i'll study that and use it
sql is very easy and very handy yes
can someone post an example of how i would use mongodb to make per server prefixes? youtube tuts are pretty bad, and i cant find relevant docs, so looking at some example code will really help me
:p
not really
that's a lot more complex and not just something i can get an example of like that
hmm
I like doing select data from table where condition
i'll look at open source bot code then
SELECT * FROM table WHERE condition
instead of SCREAMING everytime
this works too
it was literally a joke as seen by the :p
:p
how do u use cogs
by subclassing commands.Cog
load the cogs into the main file as well
thats the problem
how?
client.add_cog(Lobby)
says Lobby isnt defined
one sec im loading up python. i'll send you the example
okay
client.add_cog(Lobby(client))
try this
and add this in ur main file:
if cog.endswith(".py"):
client.load_extension(f"cogs.{cog[:-3]}")
else:
print(f'unable to load {cog[:-3]}')```
what
abspath
it'll be saying unable to load {} for files without .py extensions
this code is only meant for cogs
what does this mean: Callback for start command is missing "ctx" parameter.
@valid galleon
code pls
code for
how to delete a msg done by specific user
its like incredibly long and i have no idea where the error came.. ill the whole error . i might just be blind
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 690, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 979, in on_message
await self.process_commands(message)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 976, in process_commands
await self.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1348, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 693, in _parse_arguments
raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for start command is missing "ctx" parameter.
add the ctx parameter
for cogs, you need (self, ctx) as the first and second argument
but where? bc i did add it for every single thing
yeah thats prob whats causing it
ohhh
aight ill try that thx
you need self AND ctx
unless its in the main file. then you only need ctx
it still doesn't work
need specific code for this
user A sends hi
then user B sends hellow or other msg
.
whenever use A sends hi
user B sends some random msg
i want to delete user B message everytime when user A sends hi
helping with code would be great
it says client is a missing positional arg
is it in a cog?
yes
send the code
cog loading in main file.
client.add_cog(lobby(client))
other file
class lobby(commands.Cog):
def __init__(self, ctx):
self.client = client
self._last_member = None
@client.group(invoke_without_command=True)
async def lobby1(ctx):
await ctx.send("Lobby 1 Online.")
@lobby1.command()
async def start(ctx):
db = sqlite3.connect('my_database.db')
cursor = db.cursor()
#QUEUE CHANNEL
queue1 = client.get_channel(883963916915453962)
queue1_members = queue1.members
queue1_members_mention = []
for member in queue1_members:
queue1_members_mention.append(member.mention)
queue1_members_id = []
for member in queue1_members:
queue1_members_id.append(member.id)
random.shuffle(queue1_members_mention)
lobby1_team_a = queue1_members[len(queue1_members) // 2:]
lobby1_team_b = queue1_members[:len(queue1_members) // 2]
lobby1_team_a_mention = []
for member in lobby1_team_a:
lobby1_team_a_mention.append(member.mention)
lobby1_team_b_mention = []
for member in lobby1_team_b:
lobby1_team_b_mention.append(member.mention)
embed_lobby1 = discord.Embed(title="Teams")
embed_lobby1.add_field(name="Team A",
value="\n".join(lobby1_team_a_mention),
inline=True)
embed_lobby1.add_field(name="Team B",
value="\n".join(lobby1_team_b_mention),
inline=True)
await ctx.send(embed=embed_lobby1)
don't mind the other sh-tty code cuz its weird
yu need to include "self" along with ctx
in the async defs?
yes
okay ill try that
so it should be like this:
async def start(self, ctx):```
ah aight
did it work?
i think that bit worked, but this happened
@lobby1.command()
async def start(self, ctx):
db = sqlite3.connect('my_database.db')
cursor = db.cursor()
#QUEUE CHANNEL
queue1 = client.get_channel(883963916915453962)
queue1_members = queue1.members
queue1_members_mention = []
for member in queue1_members:
queue1_members_mention.append(member.mention)
queue1_members_id = []
for member in queue1_members:
queue1_members_id.append(member.id)
error: line 34, in start
queue1_members = queue1.members
AttributeError: 'NoneType' object has no attribute 'members'
i dont understand this it literally worked when it wasn't in a cog
Why this command not work when all it's okay
error?
oh... could u explain whats wrong here?
do this:
queue1 = self.client.get_channel(12345689)```
when using client in cogs, do self.client
still shows same error.. think this code is the one thats wrong
queue1_members = queue1.members
whats the error message
it did work in the past, and im pretty sure it does have the attribute, but ill check again
fuckin hate cogs
itâs not bad though and I like it because of organization
same
i like cogs bc you can reload them without restarting your bot
How would i convert this line into mongodb code? im referring to some examples to get started, and need to convert this code from sqlite3:
c.execute(f"SELECT prefix FROM prefix WHERE guild_id = {message.guild.id}")```
to me they feel overcomplicated for 0 reason :/
go to #databases and i think they can help ya
theyre pretty easy if you refer the docs
sure
yeah thats true
sorry for reply ping lol
its good
error?
ctx is not necessary ig
i dont think you need the content var
yeah, but you can have it if you want anyways
now help me peeps
need specific code for this
when any user sends hi
then user B sends hellow or other msg
.
whenever any user sends hi
user B sends some random msg
i want to delete user B message everytime when any user sends hi
helping with code would be great
so how to solve that? now it doesnt work
await member.send('Private message')
try this
@client.command(pass_context=True)
this isn't necessary but for some reason my code didn't work as well when i didn't have this
pass_context is deprecated since like 4 years ago iirc
it has 0 function
it's completely unused
That is not the issue with the commane
then you changed something else
i didnt
Either his bot instance is bot or thats a cog i guess
because then it actually did something
i don't think it will affect the code or command but it won't be the answer to any issue because it doesn't do anything
since 1.0 pass context isnt needed
that's literally what i said
coming from personal experience, literally only thing i changed was that and it worked. he might not be using rewrite or smtg idfk but im just saying try it out
no, it won't fix it
class HelpCommand(commands.HelpCommand):
def __init__(self):
super().__init__(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=True,
)
async def strikethrough_if_invalid(self, command: commands.Command):
try:
if await command.can_run(self.context):
return self.get_command_signature(command)
except commands.CommandError:
pass
return f'~~{self.get_command_signature(command)}~~'
async def send_bot_help(self, mapping):
ctx = self.context
hel = []
bot = ctx.bot
owner = bot.get_user(862906093373751337)
for cog, cmds in mapping.items():
if cog and await self.filter_commands(cmds, sort=True): #await self.filter_commands(cmds, sort=True)
hel.append(cog)
embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
for idx in hel:
#allowed_cmds = filter(lambda x: not x.hidden, idx.get_commands())
embed.add_field(
inline=False,
name=idx.qualified_name.title(),
value= ", ".join(map(lambda x: f"`{x}`", await self.strikethrough_if_invalid(command))), #filter(lambda x: not x.hidden, await idx.can_run(ctx))))
)
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=bot.user.display_avatar)
embed.set_footer(text=f"Made with â¤ď¸ by {owner}",icon_url=owner.display_avatar)
await ctx.send(embed=embed)
it did for me
error:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/help.py", line 836, in command_callback
return await self.send_bot_help(mapping)
File "/home/runner/help.py", line 43, in send_bot_help
value= ", ".join(map(lambda x: f"`{x}`", await self.strikethrough_if_invalid(command))), #filter(lambda x: not x.hidden, await idx.can_run(ctx))))
NameError: name 'command' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'command' is not defined
idk why dont ask
help?
@stiff nexus why copy code
what bruh
You did all that?
yes but
async def strikethrough_if_invalid(self, command: commands.Command):
try:
if await command.can_run(self.context):
return self.get_command_signature(command)
except commands.CommandError:
pass
return f'~~{self.get_command_signature(command)}~~'
``` this was advanced to add by my friend
idek what this code does/means
@client.command(name='play_song', help='To play song')
async def play(ctx,url):
try :
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
filename = await YTDLSource.from_url(url, loop=bot.loop)
voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename))
await ctx.send('**Now playing:** {}'.format(filename))
except:
await ctx.send("The bot is not connected to a voice channel.")
then why the fuck u said "why copy code"
because I know you didnt do it?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeâs robots.txt file; (b) with YouTubeâs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
getting a discord.ext.commands.errors.CommandNotFound error
We aren't gonna help
damn nvm then
Better not to judge, just leave it if you don't know how to help
đ
you cant even tell me why the console isnt finding the command?
no
also stop this it feels like you are stalking me
I'm not gonna help with anything about it, sorry
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
jeez
đ¤ˇââď¸
try:
event = await self.bot.wait_for("select_option", check=None)
label = event.component[0].label
if label =="Option 1":
await event.respond(
type=InteractionType.ChannelMessageWithSource,
ephemeral=True,
embed=e1
)
elif label =="Option 2":
await event.respond(
type=InteractionType.ChannelMessageWithSource,
ephemeral=True,
embed=e2
)
elif label =="Option 3":
await event.respond(
type=InteractionType.ChannelMessageWithSource,
ephemeral=False,
embed=e3
)
client.run("TOKEN")```
Apparently, This error is on the LAST line of my code
``` client.run("TOKEN")
IndentationError: unexpected unindent
Ok but now await is out of function
.....
await member.send(content=msg)```
it prints ```<Message id=887341517851729961 channel=<DMChannel id=887334334908989441 recipient=<User id=256524667186184192 name='Hik' discriminator='9778' bot=False>> type=<MessageType.default: 0> author=<User id=256524667186184192 name='Hik' discriminator='9778' bot=False> flags=<MessageFlags value=0>>```
how can i solve?
hey im trying to make a tictactoe command and i want to check if the player argument is a bot or member
@bot.command(aliases=['ttt'])
async def tictactoe(ctx, p1: discord.Member):
p2 = ctx.author
if p1 == discord.User.bot:
await ctx.send('u cant play against a bot')
return
This wont work and neither does
@bot.command(aliases=['ttt'])
async def tictactoe(ctx, p1: discord.Member):
p2 = ctx.author
if discord.User.bot:
await ctx.send('u cant play against a bot')
return
Here it just says all users are bots somehow
help
!role.permission
!e @client.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{ctx.author.mention} has unbanned {user} ")
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'client' is not defined
Umm
!e @commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{ctx.author.mention} has unbanned {user} ")
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'commands' is not defined
!e banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{ctx.author.mention} has unbanned {user} ")
!discord.Member
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").
`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.
`hash(x)` Returns the memberâs hash.
`str(x)` Returns the memberâs name with the discriminator.
:l
@commands.command()
async def setPrefix(self,ctx,*,prefix):
id = ctx.guild.id
sql = "UPDATE SERVERINFORMATION SET Server_Prefix = ? WHERE Server_Id = ?"
val = (prefix,id)
async with aiosqlite.connect('pikachubotdb.sqlite') as db:
async with db.cursor() as cur:
await cur.execute(sql,val)
await ctx.send(f"Prefix Has Been Set To {prefix}")
can anyone tell me error in this code because no error is coming but the data in database is not changing
Hmm well I've never used SQL but I'm pretty sure you have to commit the changes
Also that goes in #databases
ok im back with another question
Your msg variable is a a Message instance
what do you guys host your bots on?
So just so msg.content
You need to commit
uptimer
is it free?
yuh
await db.commit()
neat
Or else changes won't apply
could you slide the link?
yeah hold on
how to get total command in the bot
what a guy
me?
yeah
lol
HELP ME PLS - typeerror-not-supported-between-instances-of-str-and-int
How to display a bot avatar?
change the str to int or int to str
if i change int to str can't use ><
to what
and cant change msg cntent in to int
len(bot.commands)
idk i use replit only
i see
@stuck flare btw uptimerobot isnt a hosting site
Elaborate a bit more
no body can help me
it just pings stuff so it doesnt go offline
then what hosting site should i use?
@stiff nexus
there isnt one?
I need the bot to send its avatar to the chat
then what do you guys do to code the bot?
python?
You can get the URL of a botâs avatar by doing
bot.user.avatar_url
bro me need ur help
y use lucas ban
thanks you
like the application?
no the lang
then which ban i use
then which ban me use??
u can use heroku i guess
make ur own unban command
@ashen gale #discord-bots message
ohkk i try and dm u @boreal ravine u 1 of my devs
no
see
What exactly do you need help with?
async def send_cog_help(self, cog):
paginator = menu.MyMenu(source= menu.MySource(self.context,per_page=14), timeout=180.0, clear_reactions_after=True, delete_message_after=False)
c = 0
for cmd in cog.get_commands():
if not cmd.hidden:
_brief = "No Information..." if not cmd.short_doc else truncate_string(cmd.short_doc, 60)
paginator.add_line(f"`{cmd.qualified_name}` : {_brief}")
c += 1
paginator.title = f"{cog.qualified_name.title()} ({c})"
await paginator.start(ctx)
```object of type 'Context' has no len()
help???
Excuse me, I want to ask, how do I get my bot to get a verification logo?
Okay thanks
it has to be in 75-80 servers then u will receive an email from discord automatically
1st, the error is basic python, you should know how to fix that yourself
2nd, your error is not present in the code you're showing
It might be an issue with the paginator
Maybe check what you are supposed to pass to it?
Perhaps
async def get_prefix(Pikachu,message):
async with aiosqlite.connect('pikachubotdb.sqlite') as db:
async with db.cursor() as cursor:
await cursor.execute(f"SELECT Server_Prefix FROM SERVERINFORMATION WHERE Server_Id = {message.guild.id}")
prefix = await cursor.fetchone()
if not prefix:
prefix = prefix[0]
else:
prefix = "$"
return prefix
can anyone tell me problem with this code because as far as i think when any commands of bot is bieng used value to get_prefix will be returned > from database but commands are not working with prefix > else they are working with $
why are you doing commit() on a select operation btw?
i did this change right now cause i think that it's problem of commit otherwise commit was not there before
async def send_cog_help(self, cog):
ctx = self.context
page = []
c = 0
for cmd in cog.get_commands():
if not cmd.hidden:
_brief = "No Information..." if not cmd.short_doc else truncate_string(cmd.short_doc, 60)
embed=discord.Embed(title = f"{cog.qualified_name.title()} ({c})")
embed.add_field(name=f"`{cmd.qualified_name}`",value=f"{_brief}")
c += 1
page.append(embed)
paginator = menu.MyMenu(source= menu.MySource(page,per_page=14), timeout=180.0, clear_reactions_after=True, delete_message_after=False)
await paginator.start(ctx)
``` it says
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: send() argument after ** must be a mapping, not NoneType
and what is the issue exactly?
I didn't get it
@spring flax issue is this
yes could you explain the issue.
Now what's stable is Py-chord or nextcloud
how can i install discord.app module?
Disnake is pretty good
Good docs and easy to use
Hmmm, I just found out
according to code when a bot command is used the prefix which will be returned to get_prefix from database would be like > for xyz id,. for abc etc but the commands are not working with respective prefix of server instead they are working with $ @spring flax
ÂŻ\_(ă)_/ÂŻ
Can you share the pypi link?
!pypi disnake
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'hey':
await message.channel.send('Shalom, how it hanging')``` help me
Okey
Hmm yes yes, it looks simple, I think I want to migrate there
....?
What's the problem? You never told any error or something
it doesnt work
Error?
hold up
đ
PS C:\Users\NAME> & "C:/Users/NAME/AppData/Local/Programs/Python/Python39/python.exe" "c:/Users/NAME/Desktop/Discord bot/Main bot.py"
Traceback (most recent call last):
File "c:\Users\NAME\Desktop\Discord bot\Main bot.py", line 22, in <module>
client.run('bot token here btw')
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged
intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000129BF776AF0>
Traceback (most recent call last):
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\NAME\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Integrate your service with Discord â whether it's a bot or a game or whatever your wildest imagination can come up with.
@maiden fable
It's likely you requesting for privileged intents you don't have.
Ah ok
What's your code?
Enable those intents from Discord Developer Portal
from discord.ext import commands
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.command()
async def clear(ctx, ammount=10):
await ctx.channel.purge(limit=ammount)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'Hey':
await message.channel.send('Shalom, how is it going?')
client.run('token')```
Yea intents.members
Yeah.
U need to enable them from discord dev portal
Go enable that privileged intent in the Dev Portal.
The error tells you to go to that link, click on your App, then go to Bot, and enable the privileged intents from there.
Where is the thing? general info bot or what?
oh lol
me use pycord ._.
yeah pycord has issues
but what do you recommend
k
how do i enable intents
https://discord.com/developers/applications/<bot id>/bot
Integrate your service with Discord â whether it's a bot or a game or whatever your wildest imagination can come up with.
there
i did that
discord.Intents.all()
do i have to do anything in code?
enable it in your code
how
ok
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.
why .all() tho just use intents you need
and pass it when initializing the Bot instance
yeah, i was too lazy to type it out lol
how do i make slash commands

i want an example 
idk
how to implement this thing in code
when any user says hi
user B says hellow to any user who says hi
so i want to delete the user B msg every time when it responds to hi message
is user b a bot?
u can use on_message
it is there
i have used on msg function
just need to implement this thing
hi guys, im incredibly stupid and even reading the docs i can't figure out how to fix a problem im experiencing. My problem is this: I have a command defined as this
async def slap(ctx, member: discord.Member = None, *, argument="they had no reason!"):
if member == ctx.author or member is None:
await ctx.send(ctx.author.mention + ' slapped themselves because *' + argument + '!*')
else:
await ctx.send(ctx.author.mention + ' slapped ' + member.mention + ' because *' + argument + '!*')
to use the command you'd type something like ~slap @userpersonmanthingy this is a reasonin the arguments. I tried to make member optional by giving it a default value of None, but since the user is typing a reason afterwards the bot interprets "this" as the user and throws an error because "user" isn't a member. I wanted to use method overloading but then remembered python doesn't let you do that ):
please help i am incredibly stupid and can't for the life of me figure out how to solve this
example code would be great for me
my bot will send hellow , a bot responds random msg to hi
and i want to delete that msg using my bot
edit
thanks , but msg is random
like if some user say hi
then then a bot responds to hi with different msg every time.
so so i want my bot to delete that random msg
also the respondes random msg is in embed form
what's the random message
u can put it in a list and randomly pick one and send
well , 1000+ msg can be put in list
just need that peice of code line which will delete that unique msg
đż
@stark bobcat can you let a user not msg anything
like when a user sends anything in channel
then my bot deletes that user msg whatever it is
for example if you msg anything here
my bot will immediately delete it
yeah
on message event and message.delete
you probably just want to check like the channel/author or whatever before deleting so it doesn't delete everyone's message anywhere
what's the code to delete trageted user msg then
I just came to know I have broken Discord ToS once before
What does the "Doesnt look like anything to me" mean in the docs for api versions?
This happened like 1 month before I started bot making
await message.delete()
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleâs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
we need user id right?
message is the message object you want to delete
it's the entire message, it's one SPECIFIC message
no
but only for 1 user
an on_message event just triggers every time anyone sends a message anywhere
so in between these 2 parts you can do your filtering and such
yes, message object has the ownerid of the sender anyway.
just gonna uhh, bring this back up
im afraid i might have to resort to methods that make my code look really ugly and hacky
send() got an unexpected keyword argument 'embed_perms'
yea, nothing like that...
there is embed but nothing like embed_perms
maybe check intents @maiden fable
which ones I need
btw if your making a music bot i would be carefull - they getting sued and taken down by google
Nah, as u can see, it is just an eval haha. HunAI is an AI Chatbot
just use both, either way you would have to get verified for 1 of em. So there isnt a point in only yusing 1
Ah alr lol
where can i create colors like this?
ah got it. I need Intents.voice_states
0xcode
Private bots r ok only da big ones
hex codes
i know how it called but i want to create one
wym....?
You manually type those bro
You cannot "create" colors, if that is what you mean
there's some website like this but just for 0x code?
yeah hex codes
Just get the hex code and prefix 0x
Remove the # lol
Yea
so like 0x0007b?
Indeed
.
Can I get the link to that?
#RRGGBB or 0xRRGGBB are the same
idk tbh
@commands.command()
async def bans(self, ctx):
guild = ctx.guild
banned_user = await guild.bans()
if not len(banned_user):
return await ctx.send(f"Found Nothing")
for ba in banned_user:
paginator = QuoPaginator(ctx, per_page=14)
paginator.add_line(f"User\n`{ba[1]}` (`{ba[1].id}`)\nReason\n`{ba[0]}`")
try:
paginator.set_thumbnail(url=ba[1].display_avatar)
except:
pass
await paginator.start()
```its only sending 1 page also not adding the thumbnail
How to make a discord.py bot 24/7 like @unkempt canyon? I heard itâs something to do with setting up a server?
You can either host it on your own pc but the practical option is to pay for a vps
Ok
Cool
I used uptime robot before I realised it sucks
What was wrong with it?
uptime robot is just a robot that pings a website every few minutes to see if it's online
it doesn't actually host anything for you
owo
Whats the command so I can send upload my entire script?
!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.pydis.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.
that's because you're creating a new paginator with each ban
simply put it outside your for loop
Does anyone know why my Start.bat file is closing after every command i issue, No error codes or nothing reveald. Yet
Is there a way to make the bot online forever instead of manually clicking run on the editor ?
@warm terrace Yes! a virtual private server (VPS)
As long as you don't use heroku you are fine
Wait I thoguht it was VPN for a second lmao
if it's a small bot you can also host it on a raspberry pi
How do I use a VPS tho ?
Define.. 'small'? đ¤
I dont have a rasp PI
private, only on a few servers ig? (a pi might work for large bots too i just haven't tried)
what i like about raspberry pis is that you only pay an up-front cost, not a subscription (though obviously you have to pay for power and internet and all that)
anyway it's just an option to be aware of as well
@discord.ui.button(label='Skip to page...', style=discord.ButtonStyle.grey)
async def numbered_page(self, button: discord.ui.Button, interaction: discord.Interaction):
"""lets you type a page number to go to"""
if self.input_lock.locked():
await interaction.response.send_message('Already waiting for your response...', ephemeral=True)
return
if self.message is None:
return
async with self.input_lock:
channel = self.message.channel
author_id = interaction.user and interaction.user.id
await interaction.response.send_message('What page do you want to go to?', ephemeral=True)
def message_check(m):
return m.author.id == author_id and channel == m.channel and m.content.isdigit()
try:
msg = await self.ctx.bot.wait_for('message', check=message_check, timeout=30.0)
except asyncio.TimeoutError:
await interaction.followup.send('Took too long.', ephemeral=True)
await asyncio.sleep(5)
else:
page = int(msg.content)
await msg.delete()
await self.show_checked_page(interaction, page - 1)
Ignoring exception in view <PaginatorView timeout=60.0 children=6> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Skip to page...' emoji=None row=None>:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "/home/runner/paginator.py", line 199, in numbered_page
if self.input_lock.locked():
AttributeError: 'PaginatorView' object has no attribute 'input_lock'
Ignoring exception in view <PaginatorView timeout=60.0 children=6> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Skip to page...' emoji=None row=None>:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "/home/runner/paginator.py", line 199, in numbered_page
if self.input_lock.locked():
AttributeError: 'PaginatorView' object has no attribute 'input_lock'
```help
But how do you use a VPS ? I dont have a rasp pi so I have to use a VPS @drifting arrow @brisk fiber
you buy a vps
Ohk, is there one for free ?
Oh and also is there a queue feature in music discord bot which i can add?
i mean most free vps are insecure and have terrible connections
you can try hosting on the cloud
or hosting a bot on a device on your network such as a laptop or a rasberi pi
Hey!
anyone know how to change volume from a bot using python?
hi
@client.command()
async def afk(ctx, reason=None):
current_nick = ctx.author.nick
await ctx.author.edit(nick=f"(AFK) {ctx.author.name}")
embed = discord.Embed(description=f"{ctx.author.mention} is **AFK**: {reason}", color=(0x2E3235))
await ctx.send(embed=embed)
counter = 0
while counter <= int(mins):
counter += 1
await asyncio.sleep(60)
if counter == int(mins):
await ctx.author.edit(nick=current_nick)
embed = discord.Embed(description=f"welcome back, {ctx.author.mention} you are no longer **AFK**", color=(0x2E3235))
await ctx.send(embed=embed)
any help?
If you're the owner of the server, it can't edit your name, cause it has no power over the owner, if it's role also doesn't have any perms, or it's not the highest role in the server, or just higher than most roles, it can't edit those users either.
Oh it makes sense now cus im the owner
thanks i asked a member to test it for me it worked
thank u so much!
Alright bro, good stuff, no problem man!
:)
do you know any good library to get youtube videos or audio (to make a music command)
!yt-dl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeâs robots.txt file; (b) with YouTubeâs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
we are unable to assist with questions related to youtube-dl
yeah
or do you have good source to play audio with discordpy
not related with youtube
ÂŻ\_(ă)_/ÂŻ
uh so other question, do i need to download the audio to play it with discordpy?
no you dont but its still against tos
okay but the audio could be mine, so it's in the tos
if its yours, you're free to use how ever you like
how good of an idea is it to run a discord bot on a chomebook.
*as a 24/7 solution
Ok
it's just what i had lying around, i really don't want to pay for a vps.
you don't need much in terms of hardware to run a bot
although chromeOS is kinda like hated on and will make it more annoying
i guess what i really meant to ask was if latency would be an issue. just running it on my desktop is about 60ms. what affects latency?
API latency is often the worst part
which averages around 30-90ms depending on the day and the time
what really confuses me is any vps i've seen has around 30ms max.
latency of about 30ms max.
usually for me it's under 20 most of the time.
bot latency? like from the device to discord.
nothing? i'm just trying to figure out if running a bot on a chromebook is a good idea for latency. it confuses me that a vps can get 20ms average but just running it locally gets me 60.
you literally cannot get faster than the API latency
No the library is no longer being developed
it's your PC has to process it, then the connection over the internet, the API has to process it, then the API has to respond over the internet, then that signal comes in to your server and that has to process it again
and that's your latency
python is just a programming language
i know a vps can get 20ms. I can show you with a ss.
the founder, creator and maintainer of discord.py, danny, stopped with maintaining
ohh
but the library still works and is open source so anyone is free to fork it and work on it from there?
i'll bet 10 dollars they just got the API latency and not the true latency
they got the latency from what the API itself reports, which is the same as on https://discordstatus.com/
Welcome to Discord's home for real-time and historical data on system performance.
that's my bot. and it probably is.\
did you use bot.latency?
that is the API latency and not the true latency
yes? api response time is 63ms, yet ping is 24?
right now API response time on average is 63ms
it varies from time to time
that website just says the current average which can be 200 or 5 or 10 or 50 or whatever in a few seconds
it constantly fluctuates
It also depends on the physical distance between you and the servers
Oopsie, I am late
how can I get the bot to read a text document that stores the id, and if the text document contains its id, then make it so that the bot simply ignores it
If anything, I use a translator:) if you don't understand please let me know
msg_dump_channel = 886496848196542514
ignoreusers = []
@bot.event
async def on_message(message: discord.Message):
channel = bot.get_channel(msg_dump_channel)
if message.author == bot.user or message.author.id in ignoreusers:
return
if message.guild is None and not message.author.bot:
iduser = message.author.id
nameuser = message.author.name
text = message.content
embed = discord.Embed(title = "ĐиŃĐ˝ŃĐľ ŃООйŃонио йОŃа: ", description = (f"```css\n{ text }```"), color = 0x1f8b4c)
embed.add_field(name ="ID ĐвŃĐžŃа и ник", value=(iduser, nameuser), inline=False)
await channel.send(embed = embed)
await bot.process_commands(message)```
how do i make my bot reply to a command
Like this but in embed
you can looking in google but take```css
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
I was looking to see if anybody could help me with doing Custom Statuses. I can set the status to a game just fine with python await client.change_presence( activity=discord.Game(name="test") ) but that always has the prefix Playing (in this case Playing test). When I try to use the custom status type python await client.change_presence( activity=discord.CustomActivity(name="test") ), nothing shows up in the bot's status line. The documentation says that CustomActivity can be used in the same way as Game. https://discordpy.readthedocs.io/en/stable/api.html?highlight=presence#discord.BaseActivity
await bot.change_presence(status=discord.Status.online, activity=discord.Game("your text"))```
yeah I can get it to work with discord.Game but not discord.CustomActivity
?
the activity= portion can be set to any BaseActivity which includes Game as well as CustomActivity
CustomActivity should display the text without the "Playing" prefix which is included with the game type
ahhh
any idea?
No, I do not know how to do this, sorry
try adding the type attribute with it
it looks like the type is a return attribute?
CustomActivity cant be used on bot accounts for whatever reason: https://stackoverflow.com/questions/60055037/how-make-custom-status-discord-py
#help-grapes message
Thank you for the help!
bruh
how do i play music with discord.py? not from youtube
local files?
Hope you plan on buying licenses for every copyrighted music you are planning on playing then
need to be your own music
Or only use noncopyright music
its a mix of my own and noncopyright yes
Ok, there should be some examples on voice stuff in the github repo for discord.py
could you provide a small example here?
Just take a look at the repo
With discord tasks loop, is there any way of passing the iterations count as an argument instead of defining it in the decorator
days = 0
while (days <= 7):
bugs = (int(input("Number of bugs collect each day:")))
days += 1
bugs_collected =+ bugs
print("The total number of bugs collected was: ",bugs_collected)
im collectin bugs for 7 days and printing out the total number at the end, why isnt this working?
Hello
= import os
import discord
from discord.ext import tasks, commands
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(
command_prefix='-',
intents = discord.Intents.all()
)
== Variable interval ==
guild_id = 886022764618731592#guild id
status_keyword = '.serverlink'#The status keyword
role_id = 886025433303355442#The role id
=======================
@tasks.loop(seconds = 2)
async def statusCheck():
guild = bot.get_guild(guild_id)
role = guild.get_role(role_id)
for member in guild.members:
if status_keyword in str(member.activity) and not role in member.roles:
try: await member.add_roles(role)
except: print(f'Try to give {member.name} role, but fail')
elif status_keyword not in str(member.activity) and role in member.roles:
try: await member.remove_roles(role)
except: print(f'Try to give {member.name} role, but f
It wonât run for some reason anyone got tips
Iâm bad at coding so ye donât bully me
U gotta load .env
how to make a discord button ?
Wdym
I put token as secret
Thatâs what env was for I thought
discord components library
use discord.py 2.0 (or better yet, use pycord, see my about me)
I coded on repl
py cord??
And I am dumbass so ye
docs ? or example
see my about me
Or just type that in google and read the docs
OOO
it's a discord.py fork that i'm working on and it supports all the new features include slash commands
That is like some fork for dpy?
can u teach me plsss
or like y'all got a docs ?
Read the mf docs
what i just asked
if you join our server we have a couple thousand members so you can just ask in a help channel or look at the docs or examples
@lone lichen when I try run this happend
= import os
import discord
from discord.ext import tasks, commands
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(
command_prefix='-',
intents = discord.Intents.all()
)
== Variable interval ==
guild_id = 886022764618731592#guild id
status_keyword = '.serverlink'#The status keyword
role_id = 886025433303355442#The role id
=======================
@tasks.loop(seconds = 2)
async def statusCheck():
guild = bot.get_guild(guild_id)
role = guild.get_role(role_id)
for member in guild.members:
if status_keyword in str(member.activity) and not role in member.roles:
try: await member.add_roles(role)
except: print(f'Try to give {member.name} role, but fail')
elif status_keyword not in str(member.activity) and role in member.roles:
try: await member.remove_roles(role)
except: print(f'Try to give {member.name} role, but f
Or just type pycord in google and read the docs
Ss the code, I cant read that
Use python-dotenv library to load env
smallest ss ever
Itâ s a library called discord_components or something
Lol
Is this replit? I can't tell because it's mobile
Yes
Yes
Use local ide
Whatâs that (Iâm dumb)
Ok
And prefereably don't use a mobile device for coding
Like vscode or pycharm
LMFAOOO
I cba going on pc rn
I agree but cba
âA quick, open source Python interpreter for the iOS platform.
Create and test Python on the go. Whether you're just learning, practicing or creating a tiny snippet for your new project, the Python IDE can help you with all of that.
Debug
Quickly test and run your code in the synthetic Python consoâŚ
Ik what ide is
Ok
Ok
@lone lichen the code is here
I told u 3 times u gotta load .env file
Ok
You don't need python-dotenv if you're doing it on replit
Setting secrets sets them as enviroment variables
Hb if u just dont do it on replit
I did that
Can you run it and send the output?
Do u have all that keep awake shit?
replit is fine for writing code and stuff, it's not good for long term hosting of bots
Hacker plan
Setup logging and see what it loggs
?

import logging
Is there a way to grab how many Voice channels the bot is in across servers?
No better w logging
I mean, better to see if it errors or anything before going through all that trouble
"Confog" lmao
Typo
confog
Yes end of code?
discord.Client.voice_clients would be your best bet, It returns a list so just use len() on for the amount
No documentation found for the requested symbol.
This will set up loggind
!d discord.Client.voice_clients *
voice_clients```
Represents a list of voice connections.
These are usually [`VoiceClient`](https://discordpy.readthedocs.io/en/stable/api.html#discord.VoiceClient "discord.VoiceClient") instances.
Just do that
before your bot.run
I shall try this, thank you
Ok
Under imports preferably
No wait
Under bot = commands.Bot
It'll work anywhere before bot.run, but usually people configure logs just after the imports
Ok
Yea but dpy sets up Itâ s own logger
So just to be sure
Under defining bot
I just wanna see what dpy loggs
I've configured logs before creating a bot instance, dosen't really change it up that much
Didnât work lmao
In what way does it "not work"?
Does it give an error?
Ok then nvm what I said
How are you running it?
Google dpy logging and do what it says in the docs
what channel do i type in if i need help with selenium? pls mention me
Basic logging
See Iâm dumb
U cant google dpy logging?
Dm me
Yes
why are you using your phone to code
@slate swan try adding a print statement somewhere in your code, maybe right on the first line
then we can see if it at least runs your script
Ok
U kidding?
You can ask in a help channel #âď˝how-to-get-help
Na Iâm dead serious I donât code
But u can google?
so you dont code and youâre trying to code a discord bot
sounds a bit contradictory
nah I think they just took it from this repo
Heâs
either way, you shouldnât use repl further more a phone to code
Also u cant just jump into making bots if u cant code
what does you being shit at coding do with the fact that youâre using a phone and repl
@slate swan did the print statement work?
LMFAOOO
No lmfao
Idk lmfao
Then it looks like something might be wrong with your replit project