#discord-bots
1 messages · Page 532 of 1
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
what's the alternatives to css for styling rank cards?
css 🤨
how do I make multiple bots run off of of one file or code? i have this right now and it only does 1 bot at once ```py
import random
import discord
from discord.ext import commands
import asyncio
list = ["token1","token2"]
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print('Logged in as '+bot.user.name+' \n(ID:'+bot.user.id+') | \nConnected to '+str(len(bot.servers))+' servers | \nConnected to '+str(len(set(bot.get_all_members())))+' users')
await bot.change_presence(game=discord.Game(name='test'))
for i in list:
bot.run(i)
idk how to call the tag but you are talking about like bigger bots that run multiple instances?
no, just 2 bots running on one code
i have 2 bot tokens, and they run off one file
you could just install node and process manager 2 (pm2) and run it that way.
its not python but you can run python on it. you just need to specify the interpreter
im running it on replit im not sure if that can do mutiple languages
welp?
How do I make a discord bot that disables pings within the channel once a role is pinged and enables pings again after 10 minutes
@crystal wind yes, you actually can use ctx.message.content to check if user used aliases like
if ctx.message.content != "help":
print("it's not help command")
@crystal wind let's say you want message this is help command to be printed only if you used !help not !info or !version you could
@client.command(aliases=['info','version'])
async def help(ctx):
if ctx.message.content == '!help':
print("this is help command")
if ctx.message.content == '!info':
print("this is info command")
probably by changing the channel's overwrites to allow mentions and not allow mentions for roles and everyone/here ping. run it on asyncio.sleep() and change perms back.
Thank you so much!
np
@crystal wind also be aware of someone using command '!help ' by accident
so instead of this:
if ctx.message.content == '!help':
I would do:
if '!help' in ctx.message.content:
It can be good or bad depending on rest of your code
I'd keep with !help for the rest of the code
Ok so I didn’t touch this file today but when I go and try my avatar command it gives me this error
this is the code
@commands.command(aliases=['ava'])
async def avatar(self, ctx, *, member: discord.Member = None):
if member == None:
member = ctx.author
user = member.avatar_url
embed = discord.Embed(
title=f"{member}'s Avatar",
color=0x000100,
timestamp=datetime.utcnow()
)
embed.set_image(url=user.avatar_url)
await ctx.send(embed=embed)
you are trying to get the avatar_url of an avatar_url.
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
not what i had in mind
lol also depends on the version they are using 😂
im using rewrite
i would recommend acouple of changes to the above code:
@commands.command(aliases=['ava'])
async def avatar(self, ctx, *, member: discord.Member = None):
if member is None:
member = ctx.author
embed = discord.Embed(
title=f"{member}'s Avatar",
color=0x000100,
timestamp=datetime.utcnow()
)
embed.set_image(url=member.avatar_url)
await ctx.send(embed=embed)
how can i get this to send only once
its working again ty :)
what's the code ?
are you in a for loop anywhere?
also how are you running your bot? Have you tried commands? do they send multiple responses too?
ehh @brittle ingot may i send it in dms i don't want to have my whole anti-nuke thing here
oop just read your name
go ahead.
@slate swan async for is still a for loop which your code is inside of.
Also you are looking in the Audit log for GuildChannelDelete in a on_guild_channel_create event
@brittle ingot
bassicly i have a bot that does the webscraping and the output is much longer in the console but the bot sends only one msg in discord
is there any way to make so it sends the rest
what does it send to the console, and what does it send on discord?
it sends a string like a msg but in console it sends much more text
its sort of like he sends me one paragraph and the rest is in the console
it doesnt print the rest
can you send a ss? web scraping will return either html or json. You may want to add a check that checks if the length is above the standard discord message count of like 1024 characters per message, if it is you can split it into multiple messages like paginating and send those "pages"
bassicly how it outputs it in the console
like you see that and it will send only one of those paragraphs
@brittle ingot
i see, im just thinking.
i bassicly used bs4 and gotten the selected element then got the text then searched through the text and let it print the matching one
and you also returned the match for sending correct? stupid question i know, but i have to ask 😂
yeah the bot runs the scraping with a command
and then i put at the end return
so it sends it to the bot to print
try to print the length of the text returned from scraping and see if its above 1024 characters. Otherwise i have no clue and would recommend either getting a help channel: #❓|how-to-get-help or waiting for someone else who may know more.
i used the len command and since its 4 parts of text it returned each one the number
could that be the problem? since it all together exceeds the limit?
isn't this technically against tos now as it's a form of message sniping
@brittle ingot
selfbotting is against tos this stops users from selfbotting
hmm you are sending all 4 parts correct?
yea
Technically you are message sniping in my opinion which was recently added to be against tos, but i could be wrong
could you elaborate? first im hearing of this.
is pretinac a custom file you import? if so can i see inside that.
@brittle ingot can you add me i dont want to send private code here
dm it to me
yea accept i cant send msgs
yk the snipe command on dank memer?? well they made it against tos now
makes sense, as it is considered a breach of privacy to post something that a user has deleted for any range of reasons.
how do I make multiple bots run off of of one file or code? i have this right now and it only does 1 bot at once ```py
import random
import discord
from discord.ext import commands
import asyncio
list = ["token1","token2"]
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print('Logged in as '+bot.user.name+' \n(ID:'+bot.user.id+') | \nConnected to '+str(len(bot.servers))+' servers | \nConnected to '+str(len(set(bot.get_all_members())))+' users')
await bot.change_presence(game=discord.Game(name='test'))
for i in list:
bot.run(i)
i also tried something else
ill send that in a sec
import requests
import random
import discord
from discord.ext import commands
import asyncio
import threading
TOKENLIST = [
"token1",
"token2"
]
def your_function():
client = commands.Bot(command_prefix="992", Bot = False)
@client.event
async def on_ready():
print('Logged in as '+client.user.name)
await client.change_presence(game=discord.Game(name='HI'))
client.run(token)
return
threads = [threading.Thread(target=your_function, args=(token,)) for token in TOKENLIST]
for t in threads: t.start()
for t in threads: t.join()
i tried that^ and it didnt run
just edited it i found alot of errors and fixed it
!d asyncio.create_task
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
wait, actually its not a coro 
Do shards make things faster or slower
trying to get faster than 0.2 ms
which i didn't even know was possible
depends on how many guilds
actually, you can use this with bot.start
and it will work with mutiple bots in one file using the same code?
yes
ill see about that
asyncio.create_task(bot.start(token))
bot2.run(token)
hello
ill try this
i just want it to be 1 start command
and for it to run it for each token
i dont wanna have to manualy place them in just be able to add it to the list
how i can change webhook avatar
Getting a error that is saying tuple object has no attribute name
@bot.command()
@commands.check(is_it_me)
async def set_stat(ctx, stat, value : int, *member : discord.Member):
stats = ["HEALTH", "ATK", "DEF", "SPED", "SPAM", "XP", "MAX-XP", "SP", "FIGHTNING"]
message = ctx.message
print(member.name)
im not able to get a the name of the member object without getting a error
remove the * from *member in your params
i thought that made it optional
no
member: discord.Member=None
or
import typing
from typing import Optional
member: Optional[discord.Member]=None
ok thanks
can i get some help for making an event that deletes webhooks
an event that deletes webhooks, or command, or even a task?
@commands.command()
async def bal(self, ctx, member:discord.Member=None):
if member is None:
member = ctx.author
if member not in db.find_one({"user_id": member.id}):
``` how can i make it so if member is None it will equal the authir
@client.command(pass_context=True)
async def profile(ctx):
if ctx.message.server == None:
pass
else:
# Code```
Would I be needing intents for this?
Like to get server info
mhm
does discord.py have any feature to extract discord profile banner?
I think it's good to inable intents no matter what
!d discord Member.banner
!d discord.Member.banner
property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.banner "discord.User.banner")
ok thanks
So is it possible to not let people dm my bot and run command there without intents
simply an event if a webhook is created delete it
!d discord.ext.commands.guild_only()
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
there we go
Oh but it won't need intents right?
ye
if you add that to your commands
none of them will work in ur bots dms
and it will raise an error
Thank you.
so you can handle it and send a message if you would like
Are role icons in the API yet?
hey sorry for the ping but I forgot I was using client.commands and it doesn't have any function like that
if you are talking about discord.py then it is not being updated anymore.
no
Pycord or whatever it is called
idk
how did you define client
Pycord is just a fork of discord.py that is going to be maintained I believe
client = commands.Bot(command_prefix= '+')```
ye, so ask it in their support server
this does
Wait true. Sorry my bad.
what did you do
@client.command.guild_only()
async def streams(ctx):```
so it said it needed to be commands not command
and after I did that and ran the the query it gave me this error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "streams" is not found```
show the whole command
@commands.guild_only()
async def streams(ctx):
async with aiohttp.ClientSession() as session:
async with session.get("https://api.twitch.tv/helix/streams",
headers={"Authorization":"Bearer","Client-Id":""},params={"game_id":""}) as r:
if r.status == 200:
r= await r.json()
fl=[]
try:
for i in r.values():
for j in i:
fl.append("**{}**".format(j["user_name"])+" "+j["language"])
fl.append("https://twitch.tv/"+j["user_login"])
except:
pass
menu = menus.MenuPages(EmbedPageSourceStream(fl,per_page=14))
await menu.start(ctx)
else:
embed=discord.Embed(title="Streams", description="Hello, there's something wrong with the coding stuff ig", color=0xd98612)
embed.set_author(name="Bounty Store Bot", icon_url="https://media.discordapp.net/attachments/799319843685662720/799552038584582154/Bounty_Emote.png")
await ctx.send(embed=embed)
hmm wdym?
wheres @client.command()
v
errrr
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/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/master/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/master/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.
ty
is member.top_role.position a valid arguement
im trying to make a ban command without any errors, and ive set it up with one of the lines being elif ctx.author.top_role.position < member.top_role.position:
Sure, looks fine
it doesnt work for some reason
Well, whats the error
the forbidden error message
Care to share
yeah i just need it to print
@valid perch it skips the elif, so it goes through all that source, and on the member.ban part it says Missing Permissions
uh huh, code?
opening discord on laptop, one min
member != None: will always be true by this point, otherwise your previous statements will throw a Nonetype error
Can you add some print statements and see what runs, what doesnt etc
Ignoring exception in command ban:
Traceback (most recent call last):
await member.ban(reason = reason)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
Well you don't have permissions 🤷♀️
well i know that
bruh
elif ctx.author.top_role.position > member.top_role.position:
q = discord.Embed(color=0x2f3136, description=f' User is hoisted above you')
await ctx.send(embed=q)
return```
thats what this is for
Catch the error and say you don't have perms?
i was saving that error event for when the bot role itself didnt have permissions
but this exists for a reason
this is greater than sign not a smaller than
That doesn't check the bots role however, just the authors
have i done it the wrong way..
its supposed to be if authors top role is smaller than members top role then send that not if authors top role is greater than the members top role
okay so i flipped the arror from > to < and it works now thanks guys i would have never noticed 😭
final product thanks @kindred epoch and @valid perch
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/ubuntu/agb-final/utils/data.py", line 20, in on_message
await self.process_commands(msg)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 975, in process_commands
ctx = await self.get_context(message)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 886, in get_context
prefix = await self.get_prefix(message)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 831, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/utils.py", line 341, in maybe_coroutine
value = f(*args, **kwargs)
File "/home/ubuntu/agb-final/Cogs/mod.py", line 204, in get_prefix
return commands.when_mentioned_or(prefix)(bot, message)
UnboundLocalError: local variable 'prefix' referenced before assignment
anyone know why i randomly get this error?
def get_prefix(self, bot, message):
try:
cursor.execute(
f"SELECT prefix FROM guilds WHERE guildId = {message.guild.id}"
)
except:
pass
try:
for row in cursor.fetchall():
self.prefixes = row[0]
prefix = (
self.prefixes
if getattr(message, "guild", None)
else self.default_prefix
)
mydb.commit()
except:
pass
return commands.when_mentioned_or(prefix)(bot, message)```
how do I fix this error?
Not just traceback, send code too
uhh does it have to be in the boxed format?
Oh, I think os.getenv('T0KEN') is None
os.getenv('T0KEN') is not getting the token
I have to run the 'import os' script, as well correct?
You already have that right?
the problem there is that TOKEN was never in the env vars
did you try using this
from dotenv import load_dotenv
load_dotenv()
i have not
try the code above in the top of your code with the imports and make sure that the .env file is there
This is gonna sound really stupid of me, and I apologize for it: but I what do I put inside the parentheses?
nothing
It's late and I've been battling this code for a good minute .
Alright
so just load_dotenv()
in the .env file add this line
TOKEN=YOUR_TOKEN
if for some reason it said that dotenv doesn't exists or something, use this command on the terminal pip install python-dotenv
print("DO NOT TELL ANYONE THE TOKEN OR YOUR SERVER GETS HACKED")
I know this
Yes ofc i recommend using django
My bot's token got leaked from shady hosts and my bot started to send people messages about saving the cheetahs
or node js
the whole thing, huh?
wym?
yes like this
import discord
import os
#imports in general
from dotenv import load_dotenv
load_dotenv()
#everything else
Gave me the same error
did you make sure that the TOKEN is in the .env file
yes
it's explicit .env filename it starts with a .
some people name it token.env but that's not right
wym? i meant the filename it's explicitly required to use .env as the filename or you can do load_dotenv(filename)
that should be right. Same error?
sure
seems correct... wait let me test it on my side
Make sure it's a string
but I thought replit didn't allowed .env files to be created anymore? They tell you to use their new key system in the side bar
wait what
where tf is the key system
I mean it told me to use the side bar but also let me to create the file
wait you're using replit?
yeah... I'm starting with something... basic.
it already has a built in environmental variables no need for .env then
i thought it was an ide
so get rid of the .env?
yeah and move your token to the env in the settings
wait where in the settings?
all I got is the option to change font size and all that
oh
nvm
Below the packages tab
the token
alrighty
key = whatever_you_want
value = bot_token
done
k now do ```py
import os
token = os.environ['token']
bot.run(token)
👍
hello im pretty new to python and i recently decided to mess around by making my own discord bot and i have been having a problem wherein i want the bot to respond when someone in the chat says !hi but if the someone who responds is me it will recognize me but if it is not me it will ask for the name then the name given will be compared to a preset list and if the name matches to one of the names in the preset list it will respond with option a if not it will respond with option b but my problem is the bot is not asking for a name rather it is comparing the !hi to the list and defaulting to option b
i sent this to help peanut without knowing there is a channel specifically for discord bots
sry
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
The event is "message"
so i put wait_for after askin what is your name>
Use the check too to make sure the bot only accepts that person's answer not anyone else's
Yes
The check is a function that is passed, it's supposed to return True or False, the function takes message, you can check message.author and return True False accordingly
What Is the id number of 👍 so pls just tell me
how does one use check?
cause i found this code in which the bot waits for the user to send a hello
channel = message.channel
await channel.send('what is your name?')
def check(m):
return m.content == 'denise' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send('hello there ' + (message.content))
if message.content.startswith('denise'):
await message.channel.send(
"oh you're that stupid person master told me about")
else:
insult = get_insult()
await channel.send(insult)
by messing around i got this
its just a forfun bot for me and my friends so yeah
pretty sure this is wrong but yeah
def mycheck(message):
...
reply = await bot.wait_for("message", check=mycheck)
mycheck is called on every message sent with the message that is sent, if
the check returns True for that message, it is accepted as a reply.
reply is a message object, so you use reply.content to access what the person wrote
ohhh ok but what is supposed to be in def mycheck(message):
is it the code to check if author is the same
Indeed
Ignoring exception in command calculate:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 89, in calculate
if res.author.id == int(res.message.embeds[0].title.split('|')([1])) and res.message.embeds[0].timestamp < delta:
AttributeError: 'coroutine' object has no attribute 'author'
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/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 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'author'
/usr/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'wait_for' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
then i use reply.content to access the reply then compare it the the strings in the list yeah?
what error
Yep
What is the id number of thumbsup? It's for something and I'm on phone and I can't do that so just tell me the id number
buttons = [
[
Button(style=ButtonStyle.grey, label="1"),
Button(style=ButtonStyle.grey, label="2"),
Button(style=ButtonStyle.grey, label="3"),
Button(style=ButtonStyle.blue, label="×"),
Button(style=ButtonStyle.red, label="EXIT"),
],
[
Button(style=ButtonStyle.grey, label="4"),
Button(style=ButtonStyle.grey, label="5"),
Button(style=ButtonStyle.grey, label="6"),
Button(style=ButtonStyle.blue, label="÷"),
Button(style=ButtonStyle.red, label="←"),
],
[
Button(style=ButtonStyle.grey, label="7"),
Button(style=ButtonStyle.grey, label="8"),
Button(style=ButtonStyle.grey, label="9"),
Button(style=ButtonStyle.blue, label="+"),
Button(style=ButtonStyle.red, label="CLEAR"),
],
[
Button(style=ButtonStyle.grey, label="00"),
Button(style=ButtonStyle.grey, label="0"),
Button(style=ButtonStyle.grey, label="."),
Button(style=ButtonStyle.blue, label="-"),
Button(style=ButtonStyle.green, label="="),
],
]
def calculator(exp):
o = exp.replace('x', '*')
o = o.replace('÷', "/")
result=''
try:
result = str(eval(o))
except:
result="An error occurred"
return result
@bot.command()
async def calculate(ctx):
msg = await ctx.send(content="Loading Calculator")
expression='None'
delta = datetime.datetime.utcnow()
embed = discord.Embed(title=f'{ctx.author.name}\'s | {ctx.author.id}',description=expression,timestamp=delta)
await msg.edit(components=buttons,embed=embed)
while msg.created_at < delta:
res = await bot.wait_for('button_click')
if res.author.id == int(res.message.embeds[0].title.split('|')([1])) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == 'None' or expression == 'An error occurred':
expression = ''
if res.component.label == 'Exit':
await res.respond(content='Calculator Closed', type=7)
break
elif res.component.label == '←':
expression = expression[:-1]
elif res.component.label == 'Clear':
expression = None
elif res.component.label == '=':
expression = calculator(expression)
else:
expression == res.component.label
f = discord.Embed(title=f'{res.author.name}\'s Calculator | {res.author.id}',description=expression,timestamp = delta)
await res.respond(content='',embed=f,component=buttons,type=7)```
this
but how does one do that sorry im really new
What is the id number of thumbsup? It's for something and I'm on phone and I can't do that so just tell me the id number
Show your code.
here @dapper cobalt

I'm sorry but I'm on phone and on my way to school, I cannot read properly so I will have to pass.
yo lemon i got it to ask for a name
and it stored the str ing reply.content but how do i compare that str to see if it is in a preset list
.
What ID number?
Nothing
await ctx.add_reaction("what do I put here so that It makes a 👍 ? ")@boreal ravine
:thumbsup:
@Blank.command(aliases=["whois"])
async def userinfo(ctx, member: discord.Member = None):
await ctx.message.delete()
if not member:
member = ctx.message.author
roles = ([role for role in member.roles[1:]])
embed = discord.Embed(colour=discord.Colour.random(), title=f"User Info - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="User Name:", value=member.display_name)
embed.add_field(name="Created Account On:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined Server On:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC")+"\u0020")
if roles == []:
embed.add_field(name="Roles:", value="None")
embed.add_field(name="Highest Role:", value="None")
await ctx.send(embed=embed)
else:
embed.add_field(name="Roles:", value=", ".join([role.mention for role in roles]))
embed.add_field(name="Highest Role:", value=member.top_role.mention)
await ctx.send(embed=embed)```
How can I make my whois command to also show the time difference in account created and server joined??
subtraction
Uh that's it?
I tried that much I understood but it didnt worked
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yes?
👍 is a unicode emoji though
Ok
brb gotta do smth
try copying the emoji from internet and putting in your code
await ctx.add_reaction(":thumbsup :")
what does ctx mean here?
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
@bot.command()
async def (ctx)
whats the error
??? i meant what does ctx do here
if you wanna add a reaction to a message your gonna have to send the message first then add a reaction to the message by setting a variable to the line where u sent the message
you have self in the command
@bot.command(name="calculate")
async def interactive_calc(self, ctx): # < remove self it isnt in a cog
view = InteractiveView()
await ctx.send("Message",view=view)
hm
okay I asked my friend and he said
its because the 3rd party lib ur using isnt stable and it'll produce bugs that'll usually work in other 2.0 libs
sooo its a module problem
Can I use tasks.loop but not specific seconds? I want to use asyncio.sleep instead.
How to get offline and online members of a guild 
!d discord.Member.status
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
@slate swan thanks
i legit forget every time, but what is the syntax for passing a user as a command parameter?
user: discord.User
thankyouu ❤️
maybe because of your format? im not sure lol
hmm
is that replit
yeah
well yeah
but i'd recommend using the master version of dpy or disnake and then use discord's time format
Just use the timestamp
No need to get a master version
Get the current timestamp
yeah that works too
oh alr thx
Then format with <t:timestamp:Format>
!timestamps
Available Format are here: https://discord.com/developers/docs/reference#message-formatting-timestamp-styles
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hm
And to get the timestamp just use the time library
Anyone know how to change nickname of specific user?
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
Use the nick field
How does the test_guild thing work??
slash commands will only work in specified guild ids
And what if I want them to work in all the guilds??
You don't include it
And wait couple minutes or hours for them to get registered everywhere
it will take about 1 hour to register
And will work after that right?
Yes
So everything will be fine after 1 hour??
Oh that's good
As the name says, testing_guild
It's for testing your commands
Once they're finished and done, remove it and it will work everywhere
Cool
hiiiiiiiiii
@client.listen()
async def on_message(message):
if str(message.channel.type) == 'private':
if message.author == client.user:
return
else:
modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
message = f"{message.author.display_name}: {message.content}"
embedmodmail = discord.Embed(title="New message!", description=message, color=0x1dddee)
await modmail_channel.send(embed=embedmodmail)
await message.author.name.send("You're message has been sent.")
else:
return```
It says
str has no attribute author
async?
message = f"{message.author.display_name}: {message.content}"
You overwrote the message object to a string
np
what does async do?
it
Run in async
gives a name to a command or event?
it's normal asynchronous programming
Makes the function a coroutine
Like in JS I think it's also async
In Go it's go
But you only put go when executing the function
Which is pretty handy
You can call the function in async or not, as you will

@client.listen()
async def on_message(message):
if str(message.channel.type) == 'private':
if message.author == client.user:
return
else:
modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
message1 = f"{message.author.display_name}"
message2 = f'''From: {message.author.display_name}'''
embedmodmail = discord.Embed(title="New message!", description=message1, color=0x1dddee)
embedmodmail.set_footer(message2)
await modmail_channel.send(embed=embedmodmail)
await message.channel.send("You're message has been sent.")
else:
return```
set_footer() takes one positional argument
but two were given
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
it only takes kwargs
it does
You can't
use an invisible character
Why would you do that anyways
Just use the description if you don't use the field name
oh ight
How to reply to messages ??
Have you even tried before asking
hm
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
^
Gat it
Next try before asking
Because if you send a message with .send() you may have tried .reply() to reply to a message
^
how to check if MessageReference has reply ping?
Just use discord.Intents.default() and add the priviledged intent(s) further in your code if needed
Can I send a message to the adequately channel when my bot joins another server?
Don't ask to ask, just ask. Because right now nobody can help you..
Yes you can, use the on_guild_join event
Thank you.
How do I specify the adequately channel?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Returns a channel object, then use .send on it like always to send a message
Thank you very much
In this community, asking to ask is fine. Telling people not to ask to ask comes across as hostile to beginners, and we want to be a friendly and welcoming community to everyone.
@commands.command()
async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl=int):
if member == None:
member = ctx.author
if ctx.guild == None:
return
result = await self.find_or_insert_user(ctx.author)
user_id, guild_id, xp, level = result
cursor = await self.db.cursor()
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id))
await self.db.commit()
await ctx.send(f"{member.mention} level changed from {level} to {lvl}")
``` it show me error in my cmd cansomeone tell me what the problem
The user has already asked multiple questions and has over 2k messages. I thought they eventually knew how to ask a question. But got it 👍
Should we run it ourselves? Or can you please provide the error so we know what the problem your running into iis
Ignoring exception in command givelevel:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "d:\project\cogs\levelling.py", line 201, in givelevel
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported
What types areuser_id, guild_id, xp, level
that in my leveling command its calculte exp and leveling up the user
and thats in my give level self, ctx: commands.Context, member: discord.Member=None, *, lvl=int
What types are they? As in type(xp), etc
Also why is lvl=int, maybe you meant lvl:int
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot is True or message.guild is None:
return
result = await self.find_or_insert_user(message.author)
user_id, guild_id, xp, level = result
print(xp, level)
xp += random.randint(10, 40)
if self.calculate_level(xp) > level:
level += 1
# 1,000
await message.channel.send(f"Congratulations, {message.author.mention} You are levelled up to {level:,}.")
cursor = await self.db.cursor()
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
await self.db.commit()
def calculate_xp(self, level):
return 100 * (level ** 2)
def calculate_level(self, xp):
# Sqrt => value ** 0.5
return round(0.1 * math.sqrt(xp))
its in here
async def find_or_insert_user(self, member: discord.Member):
# user_id, guild_id, xp, level
cursor = await self.db.cursor()
await cursor.execute('Select * from users where user_id = ?', (member.id,))
result = await cursor.fetchone()
if result is None:
result = (member.id, member.guild.id, 0, 0)
await cursor.execute('Insert into users values(?, ?, ?, ?)', result)
await self.db.commit()
What's returned? Nothing?
So your tryna insert null data?
k
I have this try thingy:
try:
chan = await ctx.channel.create_invite().url
except:
chan = None
``` and in the console it says,
```py
main.py:30: RuntimeWarning: coroutine 'GuildChannel.create_invite' was never awaited
chan = await ctx.channel.create_invite().url
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
what does that mean
!d discord.Invite.url
property url: str```
A property that retrieves the invite URL.
Hmm
u dont need url
it automatically creates an invite thats a string
look in the docs
Sure. What do u have till now?
Please don't reply like this
problem is the command is not editing the database but he said its changed
and the types is this im new with sqlite3
user_id gulid_id xp level
When i asked him for his code he said nothing
Oh, hmm 🤷♂️
Is there any way to get the number of messages sent during a week?
yes
Could you tell me about it?
just count the messages in on_message event and store the count value in a database
how would i detect a bot's status?
would I get them like a normal user and use member.status?
Which lib u using? Dpy or any other fork?
Yea
How do I get a member again?
!d discord.ext.commands.Bot.get_memebr
No documentation found for the requested symbol.
uhm
I think it's guild.get_member
o mb
!rank
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
No leveling system here I think. #bot-commands.
You tell me, how are you calling it?
I understood I was missing a word
@lilac latch well it won't work because if you don't specify any argument it will give error because there is an missing argument
you have to do
async def truth(ctx, rating=None):
this way if user enters nothing it will be none and if user specifies the argument, rating will be the argument.
i keep getting this error while trying to delete channels
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
Channel's not found
Error says it all
not really its giving me the error while theirs channels that i assigned to be deleted
Is the channel getting deleted?
If not, are you sure you're getting the right channel? What's your code?
its supposed to delete multiple channels with a while loop but it just deletes one and stops and yes i added continue
What's your code?
Without code we can't help at all
its supposed to delete 100 channels with the loop but it just stops
@bot.event
async def on_message(message):
if (message.content.startswith(secretword)):
for guild in client.guilds:
for channel in guild.channels:
a = 0
while True:
if (a < 100):
a += 1
await channel.delete()
continue
elif a > 100:
break
isnt this
api abuse or something
You're doing continue
And not breaking
So it will try 100 times to delete the same channel
oh right thanks
Yes
And you're already looping through all the guild channels, why do you need again a while True loop
Just do the for loop and await channel.delete()
ok thanks
without a, without another random while loop and without another random if and else statement
Can someone help
It's .utils.get
oh thx i dont remember the syntax of this
so thats why
alr ill delete my message srry if i destroyed a convo
Then change it
why
You don't name variables with a starting capital letter, only classes
Python naming conventions
Following them is a must
python suggests you do camel case naming for variables 👍 (joke)

is on_member_kick a thing
Hey anyone know how to use "Request" module
Might need to check with the audit logs to know if the user got kicked
Pretty sure the response has a .history attribute
So like
r = requests.get("https://google.com")
r.history
Idk but this return a url that i requested
r = request.get("https://redirect.ex/redirect")
print(r.url)
Does this return final url?
Then how do i get the last one
I mean, use your common sence
uh...
It stores the history of urls, where would be the last one visited 
Then how about it redirect 4 times

Then there will be 4 elements in the list
Then how do i get only the final one
At this point it's just understanding how a list works
list[-1] always returns the last element of a list
Alright
For what is it? A command?
autoresponder
Then check the message.content
if help in message.content ```
?
simple
if "help" in message.content
it could be a list

?
I'm commenting on his code
Not all the possible options
oh cool
You can always convert 
hm
Nothing returned
Bruh
it return []
I tried requesting bit ly
no error but command would not respond
@client.command()
async def nsfw(ctx):
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
Nvm it returned response 303
Do you have any error handler
It might eat your error
ye
Does it send the embed or just nothing
How to check if my bot has the permissions to send embeds?
For a command?
will py 3.10 cause any issue with dpy?
yes
For the whole bot
embed
Where are you wanting to check the permissions
guild_permissions.embed_links
on_join
When the bot joins the server
Not all of the urls in the json are images
why not just use asyncPRAW?
Check if embed_links is in guild.me.guild_permissions
for channel in guild.text_channels:
try:
Tile = "Thanks for Adding me!!"
Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
await ctx.send(embed=embed)
except:
await ctx.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
Can someone tell me why is it not working?
Don't do this why would you ever send a message in every channel
Oh then??
Also it doesn't work cause there is no ctx defined there you would have to use channel.send instead
I changed it
Only send it in one channel
try:
Tile = "Thanks for Adding me!!"
Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
await channel.send(embed=embed)
except:
await channel.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
Now channel isn't defined lmao
-,-
what's the channel supposed to be?
@bright palm
Choose a channel to send the message in
And which channel is that supposed to be?
I want to send the message in the 1st channel
Then send it in guild.text_channels[0]
async def on_guild_join(guild):
general = find(lambda x: x.name == 'general', guild.text_channels)
try:
Tile = "Thanks for Adding me!!"
Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
await general.send(embed=embed)
except:
await general.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
Is that good?
General might not exist so it will just error in that case
general = guild.text_channels[0]
how can i make a spotify command
!d dicord.spotify
No documentation found for the requested symbol.
tf?
WDYM??
Ok so use discord.spotify ofc
!d discord.Spotify.title
property title: str```
The title of the song being played.
i had this
@client.command()
async def sp(ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title=f"{user.name}'s Spotify",
description="Listening to {}".format(activity.title),
color=0xC902FF)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(name="Artist", value=activity.artist)
embed.add_field(name="Album", value=activity.album)
embed.set_footer(text="Song started at {}".format(
activity.created_at.strftime("%H:%M")))
await ctx.send(embed=embed)```
So what's the problem?
Yeah
Is it bad to put the status of the bot in the on_ready?
Yes
hi can i have help?
What would be a good way to do it?
async def listening(ctx, *, message):
if ctx.author.id in []:
await Yui.change_presence(activity=disnake.Activity(type=disnake.ActivityType.listening, name=message))
else:
titld = "You don't have permissions?"
main = "The command you tried to use can be used only be used by the developer and people whom he gave access to. You are not allowed to use it"
embedVar = disnake.Embed(title=titld, description=main, color=bot_embed_color)
await ctx.send(embed=embedVar)```
Maybe something like this
Everyone can
from discord.ext import commands
client = commands.bot(command_prefix="?")
client.run("ODk") ```
why i cant run bot?
commands.Bot, not bot
there wass full token
And name your variable bot and not client
Traceback (most recent call last):
File "main.py", line 7, in <module>
client = commands.bot(command_prefix='!', intents=discord.Intents.all())
TypeError: 'module' object is not callable
what does this mean?
It's bot.run bro
from discord.ext import commands
bot = commands.bot(command_prefix="?")
bot.run("ODk3")```
is that good?
Yup
Nope
Check this again ^
from discord.ext import commands
bot = commands.Bot(command_prefix="?")
bot.run("ODk3")```
As I said
^
@eternal pine
?
Use that
okay
no ;/
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="?")
bot.run("O")
no i have good token
Any errors?
Token not valid
is that mean
What's the Best place to test activate these bots?
You used single quote and double quote apparently
BRUH
"' xxx '
^
why it does this
@commands.command()
async def spotify(self, ctx, user: discord.Member = None):
user = user or ctx.author
spot = next((activity for activity in user.activities if isinstance(activity, discord.Spotify)), None)
if spot is None:
await ctx.send(f"{user.name} is not listening to Spotify")
return
embed = discord.Embed(title=f"{user.name}'s Spotify", color=spot.color)
embed.add_field(name="Song", value=spot.title)
embed.add_field(name="Artist", value=spot.artist)
embed.add_field(name="Album", value=spot.album)
embed.add_field(name="Track Link", value=f"[{spot.title}](https://open.spotify.com/track/{spot.track_id})")
embed.set_thumbnail(url=spot.album_cover_url)
await ctx.send(embed=embed)```
how do i install dpy 2.0 with poetry
Traceback (most recent call last):
File "main.py", line 109, in <module>
client.run(botToken)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/opt/virtualenvs/python3/lib/python3.8/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.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
the error message says what to do
import discord
from discord.ext import commands
Bot = commands.Bot(command_prefix="?")
Bot.run("ODk3")```
anyone?
Enable intents in the developer portal
yes
what is wrong here?
where?
Everything's in the error
Follow what you're being told
there
were u listening to spotify when u did that command?
yeah
were it in your status as well?
ur status says Chrome for 1h?
my friend did it
from discord.ext import commands
bot = commands.Bot(command_prefix="?")
bot.run("ODk1")```is this good rn?
did he have it?
yes
Side note but please name variables as they should x)
yes just the variable names
what is variable names?
You should add an on_ready event to print something when the bot goes online
so whats the error
bruh
XD
are you new in python?
i dont really know
yeah, i am
@eternal pine https://vcokltfre.dev/tutorial/03-hello/
In this part, I’ll show you the basics of how to create a super simple bot and get it connected to Discord.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Please learn python before discord.py
idk why it does not works
Oh yeah, learn python first
y do u need next() though?
i had the code from long time
on my other bot
yes but why next()?
I'm pretty sure an activity isn't an iterable
maybe because the bot is trying to find the next song in the activity which it cant find
So whenever my bot starts up its on_guild_remove event fires up, any way to stop that?
tried using an if to check if the guild is None and not do anything if it is, but that doesn't help
@bot.event
async def on_guild_remove(guild):
await bot.wait_until_ready()
if guild == None or guild == " ":
pass
else:
log = bot.get_channel(botlog_spam)
await log.send("Left: " + str(guild))
^ current code
isn't that event supposed to fire whenever the bot gets removed from a server?
no, it's supposed to fire up whenever a guild enters or leaves its cache I think
thats on_guild_join
so next stop it from working?
maybe? try it I don't know lol
well I don't know why it keeps doing that then
it isn't leaving any guild
!d discord.on_guild_remove
discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
This happens through, but not limited to, these circumstances...
hm
and when it notifies me that it's leaving a guild, the guild is always None
does the bot have intents?
yes
bruh
error?
why. did. u. copy. @lyric moat's. code.
can anyone help
yeah its a stack code
the problem is in the error
^
where?
get a spot object first
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
im tryna get it to join vc but it wont
Spotify Command
i tried a lot of things and i cant get this to work
@client.command()
async def spotify(ctx, user: discord.Member = None):
embedspotify = discord.Embed(title=f"{user.name}'s
if your copying code please don't ask for help if theres an error your supposed to make a command yourself not copy code
its not showin a error
^, ESPECIALLY if you don't even understand py basics
oh
imma sit down and code a spotify code thats hard
- i got school
@lyric moat @slate swan idk what ur talking about it works?
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
yes?
we used the last one
it was the one you used
i doesnt work even tho there is not error
theres 3 diff codes there
I'm a "he" and it was this one
dont think so
@client.command()
@commands.guild_only() # We can only access activities from a guild
async def spotify(ctx, user: discord.Member = None):
user = user or ctx.author # default to the caller
spot = next((activity for activity in user.activities if isinstance(activity, discord.Spotify)), None)
if spot is None:
await ctx.send(f"{user.name} is not listening to Spotify")
return
embedspotify = discord.Embed(title=f"{user.name}'s Spotify", color=0x1eba10)
embedspotify.add_field(name="Song", value=spot.title)
embedspotify.add_field(name="Artist", value=spot.artist)
embedspotify.add_field(name="Album", value=spot.album)
embedspotify.set_thumbnail(url=spot.album_cover_url)
await ctx.send(embed=embedspotify)```
error?
Hey I have a question, So I have 10 voice channels, And me and My friend are in voice number 1, And then I move him to voice number 2 with my bot, How do I tell my bot to remember remember the first channel he was at first?
save in variable
or database
try put a bio on and try it
How do I do that?
might want to finish a python course first
before making a bot
not to sound rude
bio?
Custom Status
@slate swan ur invis + no spotify activity
try now
lol
look now
cache issue?
nope

dont think so anyways
prompt_embed = discord.Embed(title=f"{prompt_content[2][0]}", description=f"{prompt_content[2][1]}", color = discord.Colour.blue(), timestamp = ctx.message.created_at)
await ctx.send(embed= prompt_embed)
is_embed_msg = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announce_channel)
if is_embed_msg.content != "True" or is_embed_msg.content != "False":
error_embed = discord.Embed(title="Error. Can only get <True> or <False> inputs.", color=discord.Colour.red())
await ctx.send(embed=error_embed)
elif is_embed_msg.content == "True":
message_is_embed = True
elif is_embed_msg.content == "False":
message_is_embed = False
#Announcement Creation
message_title = title_msg.content
message_description = description_msg.content
await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")
Referenced before assignment
At line: await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")
message_is_embed referenced before assignment
any help?
uh
?
Hey I have a question, So I have 10 voice channels, And me and My friend are in voice number 1, And then I move him to voice number 2 with my bot, How do I tell my bot to remember remember the first channel he was at first?
as I said, store it in a variable
or in a database
assign a value to message_is_embed
on_voice_state_update maybe?
before it is used
ok but it doesnt make sence
Explain please...
okkk
@marble pilot u need to define it before using the variable
ik but
nvm
oh and i also got another error that i cant solve i am trying like 30 mins.
#Is Embed Prompt
prompt_embed = discord.Embed(title=f"{prompt_content[2][0]}", description=f"{prompt_content[2][1]}", color = discord.Colour.blue(), timestamp = ctx.message.created_at)
await ctx.send(embed= prompt_embed)
is_embed_msg = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announce_channel)
if is_embed_msg.content is not "True" or is_embed_msg.content is not "False":
error_embed = discord.Embed(title="Error. Can only get <True> or <False> inputs.", color=discord.Colour.red())
await ctx.send(embed=error_embed)
elif is_embed_msg.content == "True":
message_is_embed = True
elif is_embed_msg.content == "False":
message_is_embed = False
#Announcement Creation
message_title = title_msg.content
message_description = description_msg.content
await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")
When it asks to type true or false if u want the announcement to be an embed and i say True, it sends the error message and it prints the value False at the last line
please ping me at the reply because i gtg
wt is wrong here
commands.bot is the module
oooh yeah

its commands.Bot
import discord
from discord.ext import commands
# -------------------- Cogs --------------------
class movespam(commands.Cog):
def __init__(self, client):
self.client = client
# -------------------- Launch --------------------
@commands.Cog.listener()
async def on_ready(self):
print('Loaded Move Spam')
# -------------------- Spam Moves --------------------
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
# first_channel = (897862720538419231)
second_channel = self.client.get_channel(897862929142128650)
third_channel = self.client.get_channel(897863428092350585)
fourth_channel = self.client.get_channel(897863452624834581)
fifth_channel = self.client.get_channel(897863472715534377)
if after.channel:
if after.channel.id == (897862720538419231):
await member.move_to(second_channel)
if after.channel:
if after.channel.id == (897862929142128650):
await member.move_to(third_channel)
if after.channel:
if after.channel.id == (897863428092350585):
await member.move_to(fourth_channel)
if after.channel:
if after.channel.id == (897863452624834581):
await member.move_to(fifth_channel)
# -------------------- Cogs Setup --------------------
def setup(client):
client.add_cog(movespam(client))
# -------------------- Comment --------------------
Okay so that's my code, So I want to move the person back to the first location that he came from...
ur token showing
Nah it doesn't
ok...
u cant use it tho
!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.
not commands.bot
a CAP can change the hole thing
and don't use a Uppercase character for naming variables.
python naming convention ^
anyone?
whats the rate limit for editing a message?
hm
Anyone please?!
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 9.options.0.name: Command name is invalid
how to fix?
Using slash commands
!read error
yes but how do i know where is it?
9.options.0.name
option9
there
^
In 9.options.0.name```
show option9
Is it possible to add a button in an embed
also the flip u doing here?
why not
asking for hellp lmao
you add a button to a message which can contain an embed
ofc it is
await ctx.send(embed=embed,components=urshithere)```
didnt u think of asking me this first?
they could be using 2.0 and not some shit third party lib
Uhm guys quick question
but ik he isnt
how to put an error handler for slash commands
@_snowflake.error
async def snowflake_error(self, ctx, error):
if isinstance(error, commands.errors.MissingRequiredArgument):
await ctx.send(embed=discord.Embed(title="The given ID **NOTHING**",
description="Was never created.",
color=discord.Color.random()))
elif isinstance(error, commands.errors.CommandInvokeError):
await ctx.send(embed=discord.Embed(title="Pls gimme a valid ID man",
description="Why you do tht to me\n \nMy friend David lost his ID... Now we call him Dav",
color=discord.Color.random()))
else:
raise (error)```
my friend david lost his id.. now we call him dav
lol
mhmm?
on_slash_command_error
why is the slash command inside the command
it has tht
or something that fits that description
it isnt?
but tht will be global for all errors
from the code you sent it clearly is
i want specific
yeah ignore tht
yeah
wait
tht might be the error..... becuz of tht it isnt registered as a slash cmd maybe?
sorry if this is off topic but im having some trouble initiating cogs?
im using replit and i was just following a tutorial for a really simple bot just to get the gist of it to implement but im just getting so many errors lol
cant you just loop through the activities and find the spotify one?
ig you could
but eh, i made that code long time ago and that's as much python i knew at that time
ah yes, for loops are advanced concepts
just now i edited the gist and my code again to make it shorter and cleaner but still didn't think of applying a loop
i can tell you're being sarcastic, but trust me i really sucked at python back then
if yu guys have any spare time id appreciate any help 👍
main.py
import discord
from discord.ext import commands
import music
cogs = [music]
client = commands.Bot(command_prefix='$', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
client.run = (TOKEN)
music.py(the cog im trying to test out)
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
#-_-
def setup(client):
client.add_cog(music(client))
bad way to load cogs
@slender river it's
bot.load_extension()
error?
during runtime
is there a reason why its considered bad?
load_extension basically does what you’re doing
!d discord.ext.commands.Bot.load_extension
load_extension(name, *, package=None)```
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
i dont really know
also if u have lots of cogs ur gonna have to import them the way ur using so I suggest using a for loop to loop through the file/folder to load the "cogs"
cause i runed bot then i wanted to create command but this doesnt work but i think i write it good
@eternal pine show full file


