#discord-bots
1 messages ยท Page 11 of 1
yes?

it returns a message object
ctx.command.name
why doesnt this work? like it doesnt add an role??? no error in the console
well, ctx.message.content then
you can use a command obj as well as said, 2 different ways lol
How i can play audio in discord bot.
I'm using Replit to run bot.
?
probably ffmpeg
How i would use ffmpeg on Replit ?
plsss
because you compare message id and channel
if payload.message_id != Channel.id
wait what
what do i have to do instead?
lol
How i can record channel audio save as mp3 in discord bot??
what
like if payload.channel_id != Channel.id?
yes?
Oh btw
For missing permissions error how do I get the permissions which are required for the command?
I want to log all talk of a channel in text format by using TTS with discord Bot .
But I don't know how to save audio from channel to mp3 .
how i could do that?
How i can record channel audio save as mp3 in discord bot??
still doesnt work
probably just an error handler, then you can specify the required permissions their
I mean all commands have different required perms
I want to get the perms for the command which user sent
idk, i dont use nextcord, in dpy it wouldnt work cus, payload doesn't have attributes guild or add_roles
nextcord is pretty much the same to discord
!d discord.ext.commands.MissingPermissions.missing_permissions
The required permissions that are missing.
Got to it before me </3
all the monkey type practice came in handy
I had no clue this was a thing
Lmao, Iโm on mobile
How to fix ๐
oh, yes. i had before only on_reaction_add not on_raw_reaction_add. forgot to remove these ty
I was just gonna say
@some.error
async def some_error(ctx, error) -> None:
if isinstance(error, MissingPermissions):
await ctx.send("Missing permissions, blah blah blah.")
Code?
ye
let's see it
lol

send your code
`@commands.Cog.listener()
async def on_guild_update(self, before, after):
try:
reason = "Koaede Security | Anti Guild Update"
logs = await after.audit_logs(limit=1, action=discord.AuditLogAction.guild_update).flatten()`
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
bot anti nuke for server me , maybe..
oh
@silk fulcrum help him
why
im lazy
๐ญ WTF
lol bruh
I still don't understand where the time out is
look at the docs
I think I should change mute to time out lol
!d discord.on_guild_update
discord.on_guild_update(before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") updates, for example:
โข Changed name
โข Changed AFK channel
โข Changed AFK timeout
โข etc...
coding in hikari,
@plugin.command
@lightbulb.option("message", "Extra things you want to tell people about")
@lightbulb.option("vendor", "the person you are vouching for", type=hikari.User)
@lightbulb.option("rating", "The rating you are giving to the seller out of 10 ex, 8 = 8/10", type=int)
@lightbulb.command("rep", "reps somebody!")
@lightbulb.implements(lightbulb.SlashCommand, lightbulb.PrefixCommand)
async def embed_command(ctx: lightbulb.Context) -> None:
if ctx.author.id == ctx.options.vendor.id:
embed=hikari.Embed(title=f"**You can't vouch for yourself!**", description=f"Try to rep somebody else!", color=0xFF0000)
embed.set_footer('Made by cantthinkofausername#3155')
embed.set_thumbnail(ctx.author.avatar_url)
await ctx.respond(embed)
return
if ctx.options.rating > 7.99:
color = hikari.Color(0x00FF00)
elif ctx.options.rating > 4.99:
color = hikari.Color(0xFFFF00)
elif ctx.options.rating > .99:
color = hikari.Color(0xFF0000)
embed=hikari.Embed(title=f"**{ctx.author}'s Vouch**", description=f"Being vouched: {ctx.options.vendor.mention}\nTag: {ctx.options.vendor}\n Item: {ctx.options.item}\nRating: {ctx.options.rating}/10\nMessage: {ctx.options.message} ", color=color)
embed.set_footer('Made by cantthinkofausername#3155')
embed.set_thumbnail(ctx.author.avatar_url)
await plugin.bot.rest.create_message(1000500583339401357, embed)
await ctx.respond(f"You have succesfully repped {ctx.options.vendor.mention}! Check [#1000500583339401357](/guild/267624335836053506/channel/1000500583339401357/)")
rating = Context.options.rating
def writeToJSONFile(path, fileName, data):
filePathNameWExt = './' + path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
path = './'
fileName = 'repdata'
data = {}
data['Rating'] = f'{rating}'
writeToJSONFile('./','file-name',data) ```
`
rating = Context.options.rating
def writeToJSONFile(path, fileName, data):
filePathNameWExt = './' + path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
path = './'
fileName = 'repdata'
data = {}
data['Rating'] = f'{rating}'
writeToJSONFile('./','file-name',data) `
rep command
the part above, is supposed to save an option from the command and write it into the json file
doesnt work tho
command works just doesnt print
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
thought this was js for a hot minute ๐ฅธ
wtf is this emoji

how is it 3 argument
str(message.author) + "blalbala"
ok
or f string
You have message.author, "..." in the error message, not message.author + "..."
oh yeah also that
https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc
if you're interested
i accidentally changed it
OOP reference
if "ZombieMaster" or "Zombie Master" in message.content.casefold():
await message.add_reaction(bot.get_emoji(1002849640040906762))
am i missing something, why does this shoot up a reaction on every message regardless of context?
ok thx
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
python poo
Shortly an instance of class you are working with inside of class method
oop nothyp?
hahaaha u have no more thyp
sed
Also why not do this
if "zombiemaster" in message.content.lower().replace(" ", "")```
This is less complex imo
Simply because i did not know about this until now, thank you both ๐
Hello I use py-cord 2.0.0 and I have a problem for debug my bot
I went from version 1.7.3 to 2.0.0 and before I had no problem
why doesnt this work? :( no error in the console
but the error is the bot doesnt add the role
payload.add_roles?
what
await member.add_roles(role)
i couldnโt find something other
so i left it like that
i was unsure
bruh
so instead of payload member?
payload.member
you need a member object
but you dont have it yet
so payload.member
so payload.member.add_roles?
if role is not None:
member = payload.member
if member is not None:
await member.add_roles(role)```
check this out
who ever ever reads docs
please
correct! - those who help
and thats why we end up here ๐ฟ
thanks
l o l
idk if its pycord but i never heard of anything called slash.slash lemme check the docs
^
still doesnt work :(
i know right away people still havent opened the docs
class discord.RawReactionActionEvent
Attributes
channel_id
emoji
event_type
guild_id
member
message_id
user_id
wtfm lol
u see guild anywhere here?
:lemao:
๐ฟ ๐ช
๐ณ
...
then u need spectacles
:lemaoX776:
payload.roles
i dont we both even opened the same webpage
u prolly opened dpy docs to the future
u use guild_id fetch the guild then get all the roles
๐
what?
@bot.command(name='getpfp')
async def getpfp(ctx, member: Member = None):
if not member:
member = ctx.author
await ctx.send(member.avatar_url)
can't seem to get this to work, anyone can spot the issue?
nothing
first u can use member = member or ctx.author
instead of that if thing
2.0 or 1.7.3?
^^
i think i use 1.7.3? not sure how to check
pip show discord
yeah
or discord.py i dont remember
no no just discord
or py import discord print(discord.__version__) in code
Yeah, 1.7.3
weird
yeah it was working for me last 15 minutes ago and it stopped working now
did you import Member from discord?
im pretty sure its member.display_avatar_url
aah okay
That doesn't work, And yeah i did import member from discord, otherwise it'll throw a giant error, sadly it doesn't throw any errors when i throw that command.
in 2.0, it would be avatar.url
try printing member.avatar_url?
or just printing something to make sure that command runs
maybe that's on_message problem lol
Tried that before coming here as well
do u have on_message event?
do member.display_avatar
i do in a different function, but i don't think that matters? since that has been there for a while and it was there when it was working
on_message isnt required for getting the pfp of a user
thats 2.0
that doesnt matter
1.7.3 is getting depricated by this august end
show it's code
yes? oops
then it probably does
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if "zombiemaster" in message.content.lower().replace(" ", ""):
await message.add_reaction(bot.get_emoji(1002849640040906762))
if "fuckyou@tall elk" in message.content.lower().replace(" ", ""):
await message.reply("Silence Wench.", mention_author=False)
if "shutup@tall elk" in message.content.lower().replace(" ", ""):
await message.reply("No YOU shut up.", mention_author=False)
on_message is no where near this
oh you're coming to that.... :hmm:
Checking for mentions like this isn't a good idea, use message.mentions
Also use elif and you can bring message.content.lower().replace(" ", "") into a variable not to do the same operation multiple times
too hard
Darn it, thank you, that fixed that!
LOL
okay im lazy to find the message about Why on_message stops my commands from working
can u scan my code like that? just making sure if i did everything correct ```py
def init(self, host, user, password, database, *, initial_tables: list = None, load_right_away: bool = True):
super().init(
host=host,
user=user,
password=password,
database=database,
raise_on_warnings=True,
)
self.database = database
self.initial_tables = initial_tables or list()
if load_right_away:
self.load_initial_tables()```
oh wait its not related to discord... but it's in my bot's code anyways!
Personally I would use or [] but that doesn't really matter, the code seems ok
nice tool :lmao:
well pycharm probably does the same
but he doesnt notice some things
for this host user password stuff why not us an env file?
wdym
are the host user pass and all constant?
put those in an env file and use os.getenv('HOST')
instead of passing all those as parameters
why this is better
looks cleaner thats it
So I've got a discord bot with discord.py, I even sync it with await tree.sync(guild = discord.Object(id=GuID)), however it still doesn't show up in my server. What common mistakes might be there that I'm not aware of?
I'd say env vars are possible to use in case you can't use a file, eg. posting source code to github. You could pull the changes on the VPS and restart/update the bot automatically but if you wanted to automate that process with a workflow, you couldn't use any files unlisted in repo. Instead you could setup runner secrets and parse them as env vars
you didn't add it?
add what?
no I did
it has the register slash commands or whatever it's called, but not the send messages, is that a problem?
you invited it with enabling application commands in oauth?
or... it's called something different
here
applications.commands
does it need the send messages permission if it has the applications.commands already enabled?
no you dont require it necessarily
admin permission is the easiest way
bad practice
ever heard
by bot would only send the messages replaying to he slash command
does it need the perm or not?
turn it on for safety, doesnt hurt
I don't get this the commands still don't sync.
class client(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=GuID))
self.synced = True
print("Synced.")
I get the synced message, but the commands still don't show up. I have the bot and the applications.commands oauth scopes and the send message permission enabled. The bot is up and is in my server.
dont sync in on_ready
use a setup_hook, just rename on_ready to setup_hook
and remove self.wait_until_ready line
I removed it, this is how the log looks now:
2022-07-30 12:59:15 INFO discord.client logging in using static token
Synced.
2022-07-30 12:59:30 INFO discord.gateway Shard ID None has sent the IDENTIFY payload.
2022-07-30 12:59:30 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: cdc03e31f061cf8cf29c24898fa94f9e).
Logged in as testerbot#0578.
Here is the code:
import discord, asyncio
from discord import app_commands
class client(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
async def setup_hook(self):
if not self.synced:
await tree.sync(guild = discord.Object(id=GuID))
self.synced = True
print("Synced.")
async def on_ready(self):
print(f"Logged in as {self.user}.")
aclient = client()
tree = app_commands.CommandTree(aclient)
@tree.command(name = "ping", description = "Pong!")
async def ping(interaction:discord.Interaction):
await interaction.response.defer(ephemeral=True)
await interaction.response.send(f"My ping is {round(bot.latency * 1000)}ms!", ephemeral=True)
aclient.run(token)
yes, right, it looks good
The slash commands still don't show up.
@slate swan I edited the previous message to include the full code.
tree is undefined
the whole is synced stuff can be handled how you do it
Hello guys, I am kinda stuck with this problem. I have a bot that's been working fine for the most part except for the task that runs every hour. It will work for about a day and stop for no reason (bot still runs though). The logs only say this 28-Jul-22 15:27:43 : Got a request to RESUME the websocket. 28-Jul-22 15:27:44 : Shard ID None has sent the RESUME payload. 28-Jul-22 15:27:44 : Shard ID None has successfully RESUMED session 891364a7a1a47367cacfdaf05085ad59 under trace ["gateway-prd-main-j192",{"micros":570,"calls":["discord-sessions-blue-prd-2-24",{"micros":17}]}]. 28-Jul-22 17:57:57 : Got a request to RESUME the websocket. 28-Jul-22 17:57:57 : Shard ID None has sent the RESUME payload. 28-Jul-22 17:57:58 : Shard ID None has successfully RESUMED session 891364a7a1a47367cacfdaf05085ad59 under trace ["gateway-prd-main-bg0v",{"micros":1251,"calls":["discord-sessions-blue-prd-2-24",{"micros":19}]}]. 28-Jul-22 19:31:52 : Websocket closed with 1006, attempting a reconnect. 28-Jul-22 19:31:52 : Got a request to RESUME the websocket.
like I don't even need the tie the syncing to this variable
it's just logging the disconnection and reconnection of your bot with the gateway, no big deal
right
and the commandtree should be defined within the subclass
Yeah but my tasks stops running. It will run for a day then just stop. Bot is working fine though as I can still use commands
mhm that's weird
Here's the log of the last task that ran. ```28-Jul-22 11:44:52 : Got a request to RESUME the websocket.
28-Jul-22 11:44:53 : Shard ID None has sent the RESUME payload.
28-Jul-22 11:44:53 : Shard ID None has successfully RESUMED session 891364a7a1a47367cacfdaf05085ad59 under trace ["gateway-prd-main-gjjs",{"micros":578,"calls":["discord-sessions-blue-prd-2-24",{"micros":17}]}].
28-Jul-22 11:46:54 : [2022-07-28 11:46:54.951391] Running task. notify_delay: 0
28-Jul-22 11:46:55 : Receiving data.
{'notify': False, 'diff': datetime.timedelta(days=2, seconds=28684, microseconds=806750)}
28-Jul-22 12:46:54 : [2022-07-28 12:46:54.920771] Running task. notify_delay: 0
28-Jul-22 15:27:43 : Got a request to RESUME the websocket.
28-Jul-22 15:27:44 : Shard ID None has sent the RESUME payload.```
can a users number thingy ever change
the one exposed by the dev mode
322611698144116741
for example this one for me, wpuld it ever change
Thank you so much for your help, finally I got my first bot with slash commands working. ๐
glad to help!
that shouldn't happen, no clue
Yeah it's pretty bizzare. I might just do some trial and error until I find the problem
cool thanks
number thingy 
a task as in a discord.ext.tasks.loop?
yes
Yeah
what's the interval and what does the task do?
It runs every hour. Basically it's sort of an alarm clock. If time now is near target time then send a discord ping
black says ```py
async def close(
self,
ctx,
id: discord.Option(
int,
description="The ticket to close, either the ticket number or the channel ID",
),
reason: discord.Option(str, description="Reason for closing the ticket"),
):
...
blasphemy.
Bless PEP8 and all His style guidelines. Bless the coming and going of Him, May His passing cleanse the world. May He keep the world for his people.
A command that sends a random panda image using an api.
@commands.command()
@commands.has_permissions(kick_members=True)
async def kick(self , ctx , member : commands.MemberConverter , * , reason=None):
await member.kick(reason=reason)
await ctx.send(f'user has been kicked from server')
@kick.error
async def kick_error(self, error, ctx):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":redTick: You don't have permission to kick members.")```
why error fun hideing other errors ?
i only want to deal with one error
if other happend i want them on terminal
add
else:
raise error
after ur if statement
wrong server
is this not a right way to deal with discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions this error
Yeah you need to check for Forbidden
In this case bot itself can't ban
ohhh , and how can i deal with this error ?
Same like you dealt with the missing permissions
the bot is missing the perms?
Add elif
like what at error , XXX?
discord.Forbidden
got ir
@kick.error
async def kick_error(self, ctx,error ):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":redTick: You don't have permission to kick members.")
elif isinstance(error, discord.Forbidden) :
await ctx.send('i dont have prms to do that')
else:
raise error```
is this correct ? not working
should i make this in bot.listen ?
commands slash doesn't work with py-cord 2.0.0
saying
for this ?
no
?/
What to use slash commands with py-cord 2.0.0 ?
@limber bison try adding error = getattr(error, "original", error) to the start of error handler
in discord py i am trying to get the profile picture of the someone who used a command by ctx.author.avatar_url but its giving me an error that member object doesnt have attribute avatar_url
how to use slash commands with py-cord 2.0.0 ?
avatar.url
it was changed in dpy 2.0
Hello! I wanted to create a date base for my bot, as a result I get an error:
base.execute('CREATE TABLE IF NOT EXISTS {}(userid INT, coin INT)'.format(id))
sqlite3.OperationalError: near "796504104565211187": syntax error
The id of the server where the message was sent from is written in quotes
Here is the complete code:```py
@bot.event
async def on_message(message):
id = message.guild.id
#the error points to this line
base.execute('CREATE TABLE IF NOT EXISTS {}(userid INT, coin INT)'.format(id))
base.commit()
count = cur.execute('SELECT * FROM {} WHERE userid == ?'.format(id),(message.author.id,)).fetchone()
if count == None:
cur.execute('INSERT INTO {} VALUES(?, ?)'.format(id),(message.author.id,1))
base.commit()
print('{message.author}({message.author.id}) received 1 coin')
elif count[1] >= 0:
cur.execute('UPDATE {} SET coin == ? WHERE userid == ?'.format(id),(count+1,message.author.id))
base.commit()
print('{message.author}({message.author.id}) got {count}+1 coins')```
There are no errors in the console```py
import sqlite3
@bot.event
async def on_ready():
print('Bot is running')
global base cur
base = sqlite3.connect('databot.db')
cur = base.cursor()
ifbase:
print('DB connected')```
hmmm like bot start responding but terminal still showing same error
btw wot is this ?
oh this is a really bad idea
you should never dynamically create tables like that
you want the user's money to be different in every guild?
yes
id | guild_id | user_id | money
---+----------+---------+-------
1 | 777 | 20 | 300
---+----------+---------+-------
2 | 777 | 21 | 400
---+----------+---------+-------
3 | 778 | 20 | 5565
---+----------+---------+-------
4 | 779 | 20 | 9999
---+----------+---------+-------
5 | 778 | 21 | 0```
one table
you should have one table, with a user_id field, guild_id field and the other data you need to store, and then have a UNIQUE constraint on user_id and guild_id
and some autoincrementing primary key
ok
Anyone know how to always keep the repl alive? My discord bot keeps going offline and literally no pingers are working for me
what's that thing called when you hover your mouse over a date and it says a date in a box
idk what it's called but it's like a new thing to discord, you hover your mouse over like a box with a date in it, and it opens an additional box stating the date
this? <t:1921921912912>
Timestamp markdown is an internationalized way of displaying times/dates. The information is rendered according to the user's timezone and locale. You can find Unix timestamps here: https://www.unixtimestamp.com/, Unix timestamps are what we use for timestamp markdown.
Usage: <t:unix_timestamp:format>
Formats
| Style | Example Output | Description |
| t | 16:20 | Short Time |
| T | 16:20:30 | Long Time |
| d | 20/04/2021 | Short Date |
| D | 20 April 2021 | Long Date |
| f | 20 April 2021 16:20 | Short Date/Time |
| F | Tuesday, 20 April 2021 16:20 | Long Date/Time |
| R | 2 months ago | Relative Time |
||this is not my guide, i just saved it||
This explains it in depth
https://gist.github.com/LeviSnoot/d9147767abeef2f770e9ddcd91eb85aa
thanks
where would i go for pygithub and discord bots?
walk, step by step
@bot.event
async def on_message_delete(message):
embed6909=discord.Embed(title="{message.author} deleted a message", description="Message: {message.content}", color="Blue")
channel=bot.get_channel(961237237046079578)
await channel.send(embed=embed6909)```
Hi can anyobody tell me why this code is not working?
not working how?
when i delete a message it does not send a message
Do you get any errors?
nope
get_channel is None prolly
get_channel is returning None*, I meant
That would be AttributeError
Probable reasons:
- Could be because the message isn't in bot's cache (so basically was sent before the bot was launched)
- Messages intent is not enabled
!d discord.on_raw_message_delete listen for this to fix 1st
discord.on_raw_message_delete(payload)```
Called when a message is deleted. Unlike [`on_message_delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_delete "discord.on_message_delete"), this is called regardless of the message being in the internal message cache or not.
If the message is found in the message cache, it can be accessed via [`RawMessageDeleteEvent.cached_message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.RawMessageDeleteEvent.cached_message "discord.RawMessageDeleteEvent.cached_message")
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
If you have Intents.default() as intents the messages is already included so it can be happening only if you didn't parse any intents at all
Also you are missing f prefixes for strings
there could be an error handler
async def on_guild_join(Guild):
print("Frazer Has Been Added To A New Server!")
guild_join_embed = discord.Embed(title='Thanks for adding me! Please vote for me on top.gg: https://top.gg/bot/1001517918540017745')
await Guild.send()``` When I put this code In I get this error: AttributeError: 'Guild' object has no attribute 'send'. What's going on?
It's working now actually i put it before bot ready event
Thank you all !
Ya can't invoke a method on a Guild object (also please use lower_snake_case for function arguments), you need a TextChannel which you can get with guild.get_channel(id)
Ah ok, thank you for letting me know. I will try that out
Example
@bot.event
async def on_guild_join(guild):
channel = guild.get_channel(123456789012345678)
await channel.send(...)```
ah
will I be able to send an embed message?
because im trying to make the bot send a message when it gets added
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Thank you! ๐
How can i enable symbols in py like โบ
Bcs if i start with any sybmol code give utf error
Are there modals for v1.7?
nop
I cant use https://www.piliapp.com/symbol/
hey how to make it connects to the db once in top of the code bcz connecting it every time does not feel right :
@bot.listen()
async def on_ready():
print("readyyyyyy")
async with aiosqlite.connect("main.db") as db :
async with db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS users(id INTEGER, wallet INTEGER)")
await db.commit()
@bot.command()
async def bal(ctx,):
author_id = ctx.message.author.id
async with aiosqlite.connect("main.db") as db :
async with db.cursor() as cursor:
await cursor.execute("SELECT wallet FROM users WHERE id = ?",(author_id,))
data = await cursor.fetchone()
if data is not None:
bal = data[0]
await ctx.send(f"your balance is {bal} ")
elif data is None:
await cursor.execute("INSERT INTO users (id, wallet) VALUES(?,?) ",(author_id, 100, ))
await db.commit()
@bot.command()
async def work(ctx):
author_id = ctx.message.author.id
async with aiosqlite.connect("main.db") as db :
async with db.cursor() as cursor:
await cursor.execute("SELECT wallet FROM users WHERE id = ?",(author_id,))
data = await cursor.fetchone()
money = data[0]
await cursor.execute("UPDATE users SET wallet = ? WHERE id =?",(money+100,author_id,))
await ctx.send("you worked very hard and earned 100$")
await db.commit()
bot.run(TOKEN)
aiosqlite.connect("main.db")
this line fo code
Connect in setup_hook, and save the connection object as a bot var
can u explain more please bcz i have no idea what u talking bout
what is setup_hook
how can I mention ctx.member inside an embed?
u tried ctx.member.mention?
oh it's .mention?
ye
can u show the rest of the code for that command?
probably is not working yet because I don't know how to convert the time to seconds
yep that should works
/60?
okay, another question. How can I convert string to a certain amount of time. like for example, when I type "1h" it should convert to 3600 seconds
I know I could manually check each letter and multiply accordingly, but was wondering if there's some library that does this for me
just type this line
what
It's run once before the bot starts up, unlike on_ready
hey chat, why am i getting a strange error?
cannot import commands from discord.ext```
this happened to me 2 days ago
i changed the ide and it worked fine
idk what exactly the reason of this error
maybe its the same problem i got idk
try to change the ide
i doubt its the ide
maybe swap it around?
from discord.ext import commands
name clashing, corrupted installation or running files that use relative imports are mainly the issues
people just see an __init__ file and theyre like let me run it
i just want my bot to work xD
send the code for import
How can I ping a user in an embed?? I'm trying the code below but the embed looks like this
you cant ping a user in a title
Why does my slash command fire first and then give an error ?
the error is not in the bot console, but in the discord itself
aw :(
and does the ping inside the embed actually work?
or I need one outside?
you can mention someone in the embeds description but it wont ping them
okay, thanks
@pastel aspen I had it like that too. As I understand it, you can't write anything except text there at all
@slate swan
Why does my slash command fire first and then give an error ?
the error is not in the bot console, but in the discord itself
there is another way
send a message together with an Embed
await ctx.send(ctx.author.mention, embed=embed)
never said you cant but ok
๐ถ
hello,
'Bot' object has no attribute 'preferences'
read the error
I did, but isn't it supposed to have one?
no?
I'm following a tutorial that uses client.preferences
oh well I thought there was one, my bad
it's not like pip hid a method/property from you as a prank while installing
what do expect as respose?
response*
@slate swan
Why does my slash command fire first and then give an error ?
the error is not in the bot console, but in the discord itself
how should I know
someone woke up on the wrong side of the bed today
only have a single bed 
that has 2 sides

do you sleep under your bed?
grumpy humpty
hey guys is it possible to set the embed thumbnail to a local image on the computer?
for example i have a file called
gen.png
i want to set that as a thumbnail in an embed
how do i set?
my bot is spamming after it detects keywords
we need to see some code..
Pretty sure you can
file = discord.File("output.png")
embed = discord.Embed()
embed.set_thumbnail(url="attachment://output.png")
await ctx.send(file=file, embed=embed)
@cursive musk
try something like that
i didnt know i could use attachment://output.png
make sure the image is saved in the same directory as the bot
try it, and see what error you get ๐
i have a bad feeling about this
it might work
alright i will respond if it doeesnt work
its not really responding an image @slate swan
what code did you use
why are you using .format, and is the folder named /temp?
it will save a new file
attachement:// references attachments to the message, not where they are on your computer
how then?
take note of this example
embed.set_thumbnail(url="attachment://output.png")
@bot.listen()
async def on_message(message):
keywords = {"when", "my", "dhc", "cash", "money", "scam", "scammer", "gonna get", "give", "wait", "waiting", "ages", "taking ages", "where", "where is", "wheres", "where's", "me", "dropped", "drop", "time", "going to", "get my", "order", "ready"}
found = keywords & set(message.content.split())
keywords_found = 0
for i in found:
keywords_found += 1
if keywords_found >= 3:
await message.channel.send("Please refrain from discussing your order outside of your ticket and wait patiently. You will be pinged if cash is dropped.")```
isnt this the same?
oh i am also getting the file obj?
yes
do i have to get the obj tho?
then you attach the file to the message, and then use ``attachment://filename` to access it
when i wont send it?
will this also not send the file itself not in the embed?
alright thanks i will try it
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
What code do you have?
What code did you use
temp/ is not part of the filename
Yes, but when it's an attachment to your message, it's not in a folder
so {}gen.png?
also you should probably use f strings instead of format, they're faster
oh
okay i will do that then instead
of and what is the max width and height from a discord.Embed.image?
I don't think there's a max size, discord just scales the image
Yeah
you can upload 4k images to discord but it'll look the same in the client as a 720p image (if it loads)
like file size or dimensions
I am pretty sure discord will automatically scale it down if it's too big
oh
Yeah, there's no max size specified anywhere
๐
guys my bot is spamming
@bot.listen()
async def on_message(message):
keywords = {"when", "my", "dhc", "cash", "money", "scam", "scammer", "gonna get", "give", "wait", "waiting", "ages", "taking ages", "where", "where is", "wheres", "where's", "me", "dropped", "drop", "time", "going to", "get my", "order", "ready"}
found = keywords & set(message.content.split())
keywords_found = 0
for i in found:
keywords_found += 1
if keywords_found >= 3:
await message.channel.send("Please refrain from discussing your order outside of your ticket and wait patiently. You will be pinged if cash is dropped.")```
When your bot sends a message, that also triggers this handler
thats not the problem
genius
how do I prevent it?
Add this if statement to the start of your handler
if message.author.bot:
return
thank you my good man
If the author of the message, is a bot, it will exit the function
I am such a fool
And yeah, can tell you're coming from another language. In python, & is a bit operator. You might want and
that's what I thought too
or not thats not logic ๐
actually python is my first language
๐ญ
and someone reccomended me &
Who..
for intersection
๐คท
yeah I didn't fully read
I've never seen that operator used anywhere
!e
message = "when the"
keywords = {"when", "my", "dhc", "cash", "money", "scam", "scammer", "gonna get", "give", "wait", "waiting", "ages", "taking ages", "where", "where is", "wheres", "where's", "me", "dropped", "drop", "time", "going to", "get my", "order", "ready"}
found = keywords & set(message.split())
print(found)
@wicked atlas :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'when'}
Ohh
woah that is cool
you can always use intersect as well lol
@glossy flame :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'poo' is not defined. Did you mean: 'pow'?
.intersection() ?
@glossy flame if you want to play around with the eval command, I'd suggest doing it in #bot-commands
Ok thank friend
๐
how can I make a music bot in discord.py 2.0?
that's against tos
No, it isn't
It's only against TOS if you're using something like ytdl to download content from somewhere that dosen't allow it
really?
what do you mean by music bot?
I'm making a simple bot for my server and I just want to have a command to play music
which would basically search on youtube and play the first link
yes that is against youtube's terms of service
how are there music playing bots then
They're just breaking TOS
That's why Rythm and Groovy got taken down
well, since it's just for my small server I don't mind breaking it lol
but I guess you cant help me with it then
How to make the buttons that were attached to the embed work after restarting the bot? discord_components
youtube-dl and ffmpeg
๐ค
they're not
๐ง what is this supposed to mean
most of them have been taken down, and they're going after the ones that still are up
music bots on discord are all but dead
one of the best features of discord bots was the music thing
youtube really likes to ruin stuff
even if I make a bot for literally 1 server?
I doubt discord will take it down. they take down ones that are in a lot of servers
discord.Embed(title="", description="")
thx
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
SyntaxError: Non-UTF-8 code starting with '\95' in file file.py on line 29, but no encoding declared: see http://python.org/dev/peps/pep-0263/ for details
When i use
https://www.piliapp.com/symbol/
Any who know how to fix?
What's line 29 have?
Embed with symbols
Paste it here
and what coding editor are you in?
Kk wait
Notepad++
In Notepad++ click Encoding at the top and choose Encode in UTF-8
Test = discord.Embed(title=f"xdBot", description=f"โข Alter {arg4} \nโข Protocol {arg4} \nโข advanced {arg1}:{arg2} \nโข test 60s \n โข executor {ctx.message.author}")
Im tried but no
you sure?
Ye bcs when i remove โข its work
Press here
K
then here
@slate swan
@slate swan kk ill try
If it doesn't fix the problem I'd suggest using a different editor like VSCode or Thonny
K
Did it work?
Wait i need to restart vps
Ill ping u if it work
And ty
It might be some weird Notepad++ thing. That error you got means it doesn't support that character
@slate swan nop dont work and im tried with vscode
use different characters than
Try this โข
Yep but i need to use symbols
I'm trying to play an mp3 file in a voice channel, and I have this code
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
channel_id = 795498638951579648
channel = client.get_channel(channel_id)
await channel.connect()
guild = 710691259009990686
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
if voice_client is None or not voice_client.is_connected():
await channel.connect()
guild = 710691259009990686
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
voice_client.play(discord.FFmpegPCMAudio(executable="ffmpeg//bin//ffmpeg.exe", source="barack.mp3"))```
but it throws this error
discord.errors.ClientException: Already connected to a voice channel.```
on the second await channel.connect()
but if I remove that line, it throws
AttributeError: 'NoneType' object has no attribute 'play'```
how do I fix this?
You don't need to use utils.get() by the way, guild.voice_client returns the current voice client
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
voice_channel: discord.VoiceChannel | None = ctx.guild.get_channel(...)
if voice_channel:
voice_client: discord.VoiceClient = ctx.guild.voice_client if ctx.guild.voice_client.channel == voice_channel else voice_channel.connect()
else:
# error out here
# use voice_client however you want
@left raptor, this makes sure that your bot is either already connected to the voice channel you want, and if not, connects to it
voice_channel: None | discord.,VoiceChannel
Shouldn't it just be discord.VoiceClient?
As the whole point is to get a concrete voice client regardless of it's status before
No because get_channel can return None
The correct typehint is None | discord.VoiceChannel
Oh I thought you were talking about voice_client
Here is a perfect opportunity to use the walrus operator, e.g ```py
if voice_channel := ctx.get_channel(...):
voice_client = ctx.guild.voice_client or await voice_channel.connect()
...
Instead of using if and else
can the .play() command play from urls?
on youtube-dl?
on discord voice channel
Ohh, no?
I keep getting this error
File "G:\Python\Python310\lib\site-packages\discord\player.py", line 117, in __del__
self.cleanup()
File "G:\Python\Python310\lib\site-packages\discord\player.py", line 223, in cleanup
self._kill_process()
File "G:\Python\Python310\lib\site-packages\discord\player.py", line 188, in _kill_process
proc = self._process
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'
is there anywhere I can get help? jesus I just wanna play music for 1 server
FFmpegPCMAudio isn't a player it's just an audio source 
is FFmpegPCMAudio against the tos?
I don't think it's against discord tos
automating download from youtube and spotify is
Even if downloading was allowed you'd still have licensing issues
Lf a basic currency bot in discord.py (sample code)
Could someone help me understand why the discord generated oAuth2 generator is giving me a response back of ?error=invalid_scope&error_description=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed.
and also how can i extract the code from the browser if successful? I'm trying to get the identify scope used so I'm opening the given link instead of generating and posting it
member: discord.Member
does anyoe have good references for discord py 2.0 buttons
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
also there are plenty of examples in the official github under the /examples/views folder
ok found it thanks
That's the current syntax to typehint
!typehint
Type Hints
A type hint indicates what type a variable is expected to be.
def add(a: int, b: int) -> int:
return a + b
The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.
It's important to note these are just hints and are not enforced at runtime.
add("hello ", "world")
The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.
Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.
mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.
I need help with one of my discord bots its just 1 error code
if anybody knows python pretty well you could help me very easily thank you
Could you paste the relevant code and any errors?
so you want me to paste the error code in this chat right
!paste If it's long do it here, but if it's short, in this chat is fine
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Traceback (most recent call last):
File "main.py", line 21, in <module>
settings = json.load(open("settings.json", encoding="utf-8"))
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 8 column 5 (char 200)
thats the full error
Could you paste everything inside settings.json?
nooo that would leak my bot token and Captcha token
You can remove those
Just need to see the structure of the file
The actual data inside is not important
Looks like some things are missing, you're sure that's all of it?
{
"capmonsterKey": "",
"botToken": "",
"guildID": "",
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}
yea thats the setting.json it was working before
it says in the error that its in main.py
just gonna code block it for ease
{
"capmonsterKey": "",
"botToken": "",
"guildID": "",
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}
so you want me to use this?
No, just pasting the same thing so it looks better
Trying to figure out where line 8 column 5 is
How many items are in botAdminId?
if you could call real quick man id appreactite it
just so i can screen share
I would rather keep it here, sorry
"botAdminId": [
""
],
is kind of strange to me, you're sure there's only 1 item in there?
its gonna be probably impossible for me to get help over text because i dont know any codes
yea there is 1 item there
And the extra space underneath it is there?
Don't worry, this is not a code issue. The JSON is formatted incorrectly
so its the settings.json?
Yeah, hence the JSONDecodeError
Python can't figure out how to parse the JSON file into a dict, so it's throwing that error
But the JSON looks valid, unless something's missing
nothings missing leme try to paste your new one you sent
The one I sent was the same one you sent, I was just resending it so it had syntax highlighting
ahhh so nothing is different about it?
Nope
Hmm so what do you think i can do to fix it
"botAdminId": [
""
],
is the extra space under the "" there in your file?
cause everything in the settings.json file is the same as it was when the bot was working
hey guys, how do i let user input with a discord bot?
Nope there is not
Ah okay, can you re-send the JSON file exactly how it is, but with the important bits removed?
kinda like input("") but on discord
!d discord.Client.wait_for inside of a command
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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
ty
{
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
"",
],
"botWhitelistedId": [
"",
]
}
how do i send it like a code like you did robin
{
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
"",
],
"botWhitelistedId": [
"",
]
}
i've got it
so that's quite a bit different from the other one you sent, this is how it actually looks like within your settings.json?
Yep exactly how it looks
plugging it into a JSON validator is always a good idea
how do i fix
.pop()
Wait there is a space between botadminid in in my visual studio code could that be the issue? but im not running it with visual studio so im using replit
Error: Parse error on line 7:
...: [ "", ], "botWhitelist
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got ']'
here's the error my little JSON validator is giving me
not discord bot related
um can you maybe type the correct format cause i dont understand that
!rule 5 and this, we don't help with self bots
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
lol petty asf
relax
its not really a self bot its a business bot ahaha
@slate swan looks like you can't have trailing commas
Wait so the commas after the ids so like this?
{
"capmonsterKey": ""
"botToken": ""
"guildID": [ ""
""]
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}
For example this is not valid:
{
"some list": [
"a value", <---- can't do this
]
}
this is valid:
{
"some list": [
"a value" <---- see how there's no comma?
]
}
OOooo i get it so like this maybe?
This only applies to the last element, by the way
{
"capmonsterKey": ""
"botToken": ""
"guildID": [ ""
""]
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}
so like that? see how there is none of these ,
{
"some list": [
"item1", <---- need this since it's not the last one
"item2" <----- no comma since last element
]
}
Your guildID list needs a comma since there are more than 1 element
if you just want a bot config in other file you can use something like a yaml file or .env
yaml โ๏ธ
Wait can you type it out for me like this {
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
"",
],
"botWhitelistedId": [
"",
]
}
but in the correct format
I don't understand how to make use of this code because I'm not trying to code a command
I'm trying to just make it play audio in the voice channel from script
with no user input required
Ah right didn't see that
so I don't have access to ctx
But you're way too much stuff in on_ready
yeah that works like json but a bit easy to configure
personally hate yaml... but at the end of the day, yaml, json, .env are all different formats and do the same thing
Robin could you type it in the correct format for me like these ,
also appreciate you for helping
just remove the trailing commas from here and you should be good
Dude im a noobie what is a trailing comma like the last comma in the end of the code
only the last items in a list can't have commas
the last comma for the last element of a list
I guess I just don't understand why I can't do this
voice_channel = get_channel(my_channel_id_number)
if bot is in voice channel:
voice_channel.play(my_audio_file)```
so basically
list = ["item1", "item2", "item3"]
^ no comma here (this is the trailing comma if there was)
like this always returns None
discord.utils.get(bot.voice_clients, guild=guild)```
because bot.voice_clients returns None
Wait can you just remove the trailing commas and send it here
list = ["item1", "item2", "item3", ]
^ โ
We're not allowed to spoonfeed, I'd rather have you fix it on your own, as you're already really close
running it hopefully fixed it
but if I know the voice channel id number, why do I need bot.voice_clients, why can't I just pass the channel to this utils.get() function directly
ahhh it didn't fix it man i think im just breaking it even more this is frustrating
i did this and its not working
Well no, that was just an example
are you sure its a settings.json issue?
Yes
JSON hates trailing commas, vscode would usually tell you where it is but I'm guessing you aren't using it
It's 2 characters that need to be removed, but I'd rather have you get there yourself so you know how to fix them
yea i understand that leme try to figure this out
"botAdminId": [
"",
],
"botWhitelistedId": [
"",
]
i see 2 trailing commas here, which are the problem
Yea but those have tokens and ids in them aren't they suppose to have trailing commas
Regardless of what's in them, trailing commas are invalid JSON
"botAdminId": [
"", <---- needs to go โ
],
"botWhitelistedId": [
"", <---- needs to go โ
]
just removed them both and ran it now i get this
Traceback (most recent call last):
File "main.py", line 27, in <module>
used = json.load(open("used.json"))
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Alright, could you send how it looks like now? With the important bits removed of course
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Use json instead of py like:
```json
your code here
```
{
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}
so what does that mean
This is an error in a different file, in used.json
Nothing is inside of used.json lmao
That's the problem
is it even possible to play an mp3 file in a voice channel without using a command? I've been googling it for hours and I haven't found a link talking about it
Empty JSON files need to have {}
You could set up a loop that runs at a specific time interval
so i put this inside of the empty used.json {}
that runs what? everything I've seen on how to play audio uses ctx
The audio
right but where do I find the discord.py function that runs audio without ctx
Bro even bigger error now wtf
You don't need context, just the voice client
how do I get the voice client without ctx
um dude the error is even bigger
Let's see it
cause this sure doesn't work
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)```
to big to put in here
guild = bot.get_guild(id)
guild.voice_client
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this returns None
guild = bot.get_guild(guild_id)```
And guild_id is the actual ID of a guild your bot is in?
yes
Where are you doing it, in on_ready?
guild being server right
Right
yes in onready
ooh yikes. Ratelimited
Temporarily banned
so your asking if the guild id is my bots id right?
I was talking to ducky wizard, sorry
Anyway possible you can get in a voice chat with me to make things easier on my life
There's nothing much you can do for this error. You've been temporarily banned
tf does that mean
The best way to not have this happen in the future is to not use replit, as it's usually the cause for it
Means you can't use the API for a certain amount of time
what do i have to create new?
Nothing. Just wait it out, think it's about half an hour? not sure though
am I supposed to be calling the code before or after await channel.connect()?
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
channel_id = 795498638951579648
channel = client.get_channel(channel_id)
await channel.connect()
guild_id = 710691259009990686
guild = bot.get_guild(guild_id)
voice_client = guild.voice_client
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
voice_client.play(discord.FFmpegPCMAudio(executable="ffmpeg//bin//ffmpeg.exe", source="barack.mp3"))```
its for sure not a hour because this has been happening since yesterday are you sure im banned?
The owner of this website (discord.com) has banned you temporarily from accessing this website.
yes
Dam why do you think it did that
Wait out the ban for now, and for it to not happen again stop using replit as it's honestly pretty bad
Shared IPs
i dont share this with anybody
You do
whats a good website i can use like replit
How so?
VSCode, Pycharm, vim, emacs
Replit's machines are underpowered, so they can have a supercomputer and let potentially hundreds of people use it at once
Godam
Bottom line is you're not the only one using that replit host machine
so vscode is a website or you talking about the app
The app
its a private one i paid for though
Are you on the hacker plan?
nah just private code or whatever 1.50 a month
so nobody can access it
Pretty sure you still share the machine itself with other people
It's not about someone else accessing your specific repl
It'd be a huge waste if replit gave one machine to each person
Good thing is, vscode is completely free & open source so you don't have to deal with replit anymore
i dont know how to keep my bot up 24/7 with Vscode app
i know how to do it with replit though
Oh no, for that you'll have to buy a VPS. VScode is just the editor
It'll go down a lot, as they're not meant for long running apps
See the pins in #965291480992321536 for more information
So is it best to keep offline unless im using it?
If your bot is still in development, there's no reason for it to be online 100% of the time. Just run it while you're coding it. Once you're ready for the general public to use it, buy a VPS and host it on there
Personally I used a raspberry pi to host my bot, which is an excellent little machine, barely used any power and was tiny & headless. Then I moved my bot to AWS, which I don't recommend for beginners as it's an enterprise business solution
how much is a good vps?
Are you looking for a down payment like a raspberry pi, or recurring payments like cloud service providers?
best cheapest
Definetely take a look at the pins in #965291480992321536 then
!d discord.Guild.voice_client use this
and if your bot restart while the bot is in a VC, it will still considered disconnected
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
hey guys, for some reason my bot wont execute commands when i have the "on message" events. do you guys know why or how i can have both? i can provide the code as well
Change the .event to .listen()
is this Standard 1GB
Lightning
$3
/month
1 vCPU
1 GB Ram
15 GB NVME Storage
1 Gbps Down / 100 Mbps Up
Private Networking
Unmetered Bandwidth
Weekly Backups
Live chat support
is this good or trash
thank u so much my guy โค๏ธ
Decent for the price, though I'd watch from who you get it for
From python website
But looking at the specs in a vacuum, it's pretty terrible lol
fk this is so annoying right now um do you have a website that have good bots for 5$ or below per month
1 vCPU
2 GB Ram
20 GB NVME Storage
1 Gbps Down / 500 Mbps Up
Private Networking
Unmetered Bandwidth
Weekly Backups
Live chat support
this better?
Little bit yeah, but the other one will do for a pretty simple discord bot
They're not all that process intensive
Wait so if i buy that will i be able to enter my code in it right?
You'll have to write up your code on something like vscode, then transfer it to your production server. Usually people will set up CI/CD to do this automatically with github
if i get the vps could you show me how to put it on my vps i already have the code ritten on vscode
discord.Guild.voice_client.play(discord.FFmpegPCMAudio(executable="ffmpeg//bin//ffmpeg.exe", source="barack.mp3"))
throws this error
AttributeError: 'property' object has no attribute 'play'```
It should be pretty easy yeah, but it depends on the VPS you get it from. They'll have instructions on how to get into it
GalaxyGate Hosting
you should be using an instance of discord.Guild, not the class itself.
#discord-bot-hosting
is that good or trash
It's good. Pretty sure GalaxyGate lets you SSH in
how do I initialize it
um whats ssh meaning
Secure Shell, let's you log into the VPS as if you were sitting in front of it with a keyboard and mouse connected, and execute commands or do anything you want on it really
Don't think that's possible due to a parsing ambiguity
You could make a subcommand, but that's cheaty and not the intended usecase
Nice so if i buy this Vps right now how would i run my vs code on it
"Cheaty" because subcommands are not meant as a "use spaces in your command free card"
Get all your code files onto the SSH using something like SCP, install python on the machine, and just run it
Yeah but.. not ideal
like this?
voice_client = discord.Guild.voice_client()```
this makes an instance of the voice client class?
Can i buy it real quick and could you possibly show me how to put it on the vps?
I could tell you sure, but mostly it's stuff you'd need to do on your own
(it's not very difficult either)
You make instances of a class and the class here is discord.Guild
this returns None though
guild = bot.get_guild(guild_id)```
so how do I get an instance of a discord.Guild
Then fetch_guild
Try fetching
guild = await bot.fetch_guild(guild_id)
AttributeError: 'NoneType' object has no attribute 'request'```
Full traceback please?
Learn to speak Bot#1741 has connected to Discord!
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\python\Audio\discord_bot.py", line 32, in on_ready
guild = await bot.fetch_guild(guild_id)
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1188, in fetch_guild
data = await self.http.get_guild(guild_id)
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
AttributeError: 'NoneType' object has no attribute 'request'```
Hmmm looks like something's awry with the internals
bot isn't None, I just checked that
Man i suck at instructions on text can you pweety please help a g out ina cal
and the guild id is right
No, bot.__session is None though for some reason
oh
could it be because I keep running the script with the bot already in the voice channel
And this is in your on_ready?
since nothing in my code tells it to leave
yes
Do you have the proper intents?
how do I check that
!intents
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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
@sick birch are you sure you would be able to help me over text 100% if i bought this vps
why do suddenly embeds look all streched?
yeah, though maybe not in one sitting as I've got to head out soon. You can ask in #965291480992321536 and anyone can help
is there a way to avoid this?
@left raptor should be intents.guilds = True for you
or just for testing purposes do discord.Intents.all()
Can someone help me with this discord bot in a call
like they are always the maximum lenght
Not much you can do
ok I put that code in but still the attribute error
The way discord embeds are shown are kind of strange to be honest
with intents.guilds to true
that's sad, it looks terrible
Is it turned on in your dashboard?
let me check
Well, it's a chat app and not a frontend UI framework so haha
i guess haha
@sick birch Bro my bot randomly started working lol
its up now
im not sure how but it is
where do I turn it on
