#discord-bots

1 messages ยท Page 11 of 1

slate swan
#

Yeah

#

ctx.message?

silk fulcrum
slate swan
slate swan
hardy yoke
swift pumice
#

why doesnt this work? like it doesnt add an role??? no error in the console

silk fulcrum
slate swan
#

you can use a command obj as well as said, 2 different ways lol

slate swan
#

Ty

royal bone
#

How i can play audio in discord bot.
I'm using Replit to run bot.
?

royal bone
silk fulcrum
#

if payload.message_id != Channel.id

swift pumice
#

what do i have to do instead?

silk fulcrum
#

compare channel id to channel id?

#

not message id to channel id

slate swan
#

lol

royal bone
#

How i can record channel audio save as mp3 in discord bot??

swift pumice
silk fulcrum
#

yes?

swift pumice
#

ok

#

thanks

slate swan
#

Oh btw
For missing permissions error how do I get the permissions which are required for the command?

royal bone
#

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??

swift pumice
slate swan
#

I mean all commands have different required perms
I want to get the perms for the command which user sent

silk fulcrum
swift pumice
#

nextcord is pretty much the same to discord

torn sail
unkempt canyonBOT
indigo pilot
torn sail
slate swan
indigo pilot
#

Lmao, Iโ€™m on mobile

slate swan
#

How to fix ๐Ÿ˜”

swift pumice
slate swan
#

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.")
slate swan
slate swan
slate swan
silk fulcrum
#

lol

slate swan
slate swan
slate swan
# slate swan 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

unkempt canyonBOT
#

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.

slate swan
#

@slate swan

#

also what is the goal for that ?

slate swan
#

oh

#

@silk fulcrum help him

silk fulcrum
#

why

slate swan
#

I'm lazy

silk fulcrum
#

im lazy

slate swan
#

๐Ÿ˜ญ WTF

silk fulcrum
#

lol bruh

slate swan
#

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

unkempt canyonBOT
#

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...
frank jacinth
#

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

slate swan
#

json fiel pepecri

#

camel case function nnames pepecri

unkempt canyonBOT
#

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.

vocal snow
vocal snow
slate swan
glossy flame
#

how is it 3 argument

silk fulcrum
#

is third

glossy flame
#

eh

#

ill be honest

#

ive never understood why self exists and what it does

silk fulcrum
glossy flame
#

ok

silk fulcrum
#

or f string

vale wing
silk fulcrum
#

oh yeah also that

glossy flame
#

i accidentally changed it

vale wing
#

OOP reference

slate swan
#
    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?

unkempt canyonBOT
#

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.")
glossy flame
#

python poo

vale wing
silk fulcrum
#

oop nothyp?

glossy flame
#

hahaaha u have no more thyp

silk fulcrum
#

sed

vale wing
#

This is less complex imo

slate swan
#

Simply because i did not know about this until now, thank you both ๐Ÿ˜

slate swan
#

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

shrewd apex
#

sed

#

send code as text the whole traceback and code for the command

slate swan
#

I don't have a traceback

#

code full ?

slate swan
swift pumice
#

why doesnt this work? :( no error in the console
but the error is the bot doesnt add the role

swift pumice
#

what

silk fulcrum
#

you even said that you accidentaly didnt remove it

#

but it's still here

slate swan
#

await member.add_roles(role)

swift pumice
#

so i left it like that

#

i was unsure

silk fulcrum
#

bruh

swift pumice
silk fulcrum
#

payload.member

#

you need a member object

#

but you dont have it yet

#

so payload.member

swift pumice
#

so payload.member.add_roles?

slate swan
#
if role is not None:
            member = payload.member
            if member is not None:
                await member.add_roles(role)```
silk fulcrum
slate swan
silk fulcrum
#

correct! - those who help

shrewd apex
#

and thats why we end up here ๐Ÿ—ฟ

swift pumice
silk fulcrum
shrewd apex
#

idk if its pycord but i never heard of anything called slash.slash lemme check the docs

swift pumice
shrewd apex
#

its bot object. slash_command()

#

not slash()

swift pumice
#

still doesnt work :(

shrewd apex
#

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
shrewd apex
#

u see guild anywhere here?

silk fulcrum
shrewd apex
#

๐Ÿ—ฟ ๐Ÿ”ช

silk fulcrum
#

๐Ÿ˜ณ

shrewd apex
#

...

swift pumice
#

but i do tho

shrewd apex
#

then u need spectacles

swift pumice
#

so just guild.roles?

#

@shrewd apex

#

i meant

silk fulcrum
#

:lemaoX776:

swift pumice
#

payload.roles

silk fulcrum
#

guess the letter

#

hangman starts

shrewd apex
#

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

swift pumice
#

๐Ÿ˜”

silk fulcrum
#

or payload.member.guild

#

or Channel.guild

#

or Role.guild

swift pumice
#

what?

slate swan
#
@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?

silk fulcrum
#

nothing

silk fulcrum
swift pumice
#

ill just look up a yt vid

#

thanks for the help

silk fulcrum
#

instead of that if thing

silk fulcrum
#

^^

slate swan
#

i think i use 1.7.3? not sure how to check

silk fulcrum
#

pip show discord

native maple
#

yeah

silk fulcrum
native maple
#

no no just discord

silk fulcrum
#

or py import discord print(discord.__version__) in code

slate swan
#

Yeah, 1.7.3

silk fulcrum
#

weird

slate swan
#

yeah it was working for me last 15 minutes ago and it stopped working now

silk fulcrum
#

did you import Member from discord?

native maple
#

im pretty sure its member.display_avatar_url

silk fulcrum
#

its 1.7.3

native maple
#

aah okay

slate swan
#

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.

silk fulcrum
#

in 2.0, it would be avatar.url

native maple
#

ah yes yes

#

i made that long time back ๐Ÿ˜‚

silk fulcrum
#

or just printing something to make sure that command runs

#

maybe that's on_message problem lol

slate swan
#

Tried that before coming here as well

silk fulcrum
#

do u have on_message event?

native maple
#

do member.display_avatar

slate swan
#

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

native maple
#

on_message isnt required for getting the pfp of a user

shrewd apex
native maple
#

first update to 2.0 ๐Ÿ˜ฉ

#

oh yeah keep forgetting ๐Ÿ˜”

#

update to 2.0 ma guy ๐Ÿ˜ฉ

silk fulcrum
#

that doesnt matter

native maple
#

1.7.3 is getting depricated by this august end

silk fulcrum
#

then it probably does

slate swan
#
@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)
native maple
#

on_message is no where near this

silk fulcrum
#

i dont see bot.proccess_commands

#

await bot.process_commands(message)

native maple
#

oh you're coming to that.... :hmm:

vale wing
#

Also use elif and you can bring message.content.lower().replace(" ", "") into a variable not to do the same operation multiple times

silk fulcrum
#

too hard

slate swan
silk fulcrum
slate swan
#

i knew i forgot something hnnnnnnnnnnnnng

#

yes you are finally

silk fulcrum
#

okay im lazy to find the message about Why on_message stops my commands from working

silk fulcrum
# vale wing Checking for mentions like this isn't a good idea, use `message.mentions`

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!

vale wing
#

Personally I would use or [] but that doesn't really matter, the code seems ok

silk fulcrum
#

nice tool :lmao:

#

well pycharm probably does the same

#

but he doesnt notice some things

shrewd apex
shrewd apex
#

are the host user pass and all constant?

silk fulcrum
#

i get them from config

#

config.toml to be precise

shrewd apex
#

put those in an env file and use os.getenv('HOST')

#

instead of passing all those as parameters

silk fulcrum
#

why this is better

shrewd apex
#

looks cleaner thats it

warm trail
#

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?

vale wing
#

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

warm trail
#

add what?

silk fulcrum
#

bot

#

on the server

warm trail
#

no I did

silk fulcrum
#

oauth...

#

ok then no idea

warm trail
#

it has the register slash commands or whatever it's called, but not the send messages, is that a problem?

silk fulcrum
#

you invited it with enabling application commands in oauth?

#

or... it's called something different

#

applications.commands

warm trail
#

does it need the send messages permission if it has the applications.commands already enabled?

slate swan
#

no you dont require it necessarily

silk fulcrum
#

admin permission is the easiest way

slate swan
#

bad practice

warm trail
#

yeah

#

never heard of least privilege?

silk fulcrum
#

ever heard

warm trail
#

does it need the perm or not?

slate swan
warm trail
#

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.

slate swan
#

use a setup_hook, just rename on_ready to setup_hook

#

and remove self.wait_until_ready line

warm trail
# slate swan dont sync in on_ready

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)
warm trail
#

The slash commands still don't show up.

#

@slate swan I edited the previous message to include the full code.

warm trail
#

the whole is synced stuff can be handled how you do it

slate tundra
#

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.

warm trail
#

like I don't even need the tie the syncing to this variable

slate swan
slate swan
#

and the commandtree should be defined within the subclass

slate tundra
slate tundra
# slate swan 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.```

glacial echo
#

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

warm trail
slate swan
slate tundra
glacial echo
slate swan
vocal snow
#

yes

slate tundra
vocal snow
slate tundra
vocal snow
#

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"),
):
...

vocal snow
#

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.

slate swan
#

give me some command suggestions

vocal snow
#

sit, fetch, bite

#

Roll over

cloud dawn
limber bison
#
 @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

paper sluice
#

add

else:
  raise error

after ur if statement

limber bison
#

!kick @limber bison jghoiegr

#

!kick @limber bison jghoiegr

paper sluice
#

wrong server

limber bison
#

f sory

#

lol

limber bison
vale wing
#

In this case bot itself can't ban

limber bison
vale wing
#

Same like you dealt with the missing permissions

slate swan
#

the bot is missing the perms?

vale wing
#

Add elif

limber bison
vale wing
#

discord.Forbidden

limber bison
#
 @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 ?

slate swan
#

commands slash doesn't work with py-cord 2.0.0

limber bison
#

asking or saying ?

slate swan
slate swan
#

no

limber bison
#

?/

slate swan
#

What to use slash commands with py-cord 2.0.0 ?

vale wing
#

@limber bison try adding error = getattr(error, "original", error) to the start of error handler

tired notch
#

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

slate swan
#

how to use slash commands with py-cord 2.0.0 ?

slate swan
#

it was changed in dpy 2.0

tired notch
#

oh ok

#

thanks

swift imp
#

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')```
limber bison
#

btw wot is this ?

vocal snow
#

you should never dynamically create tables like that

swift imp
#

ok

#

thx

vocal snow
#

you want the user's money to be different in every guild?

swift imp
#

yes

silk fulcrum
#
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

vocal snow
#

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

swift imp
#

ok

glossy flame
#

Anyone know how to always keep the repl alive? My discord bot keeps going offline and literally no pingers are working for me

scarlet aurora
#

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

scarlet aurora
#

YES

#

how do you do that

#

12 April 62873 15:01

silk fulcrum
#

wait a minute

#

ill find full info about it

#

cus i just did <t:1921921912912>

scarlet aurora
#

<t:1921921912912>

#

how da hell does that work

swift imp
#

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||

kindred kernel
#

oh

#

im late

sick panther
scarlet aurora
#

thanks

echo wasp
#

where would i go for pygithub and discord bots?

slate swan
arctic gyro
#
@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?
arctic gyro
sick birch
#

Do you get any errors?

arctic gyro
#

nope

slate swan
#

get_channel is None prolly

arctic gyro
#

the id is correct

#

of the channel

slate swan
vale wing
#

That would be AttributeError

vale wing
#

!d discord.on_raw_message_delete listen for this to fix 1st

unkempt canyonBOT
#

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.
vale wing
#

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

slate swan
vale wing
#

That's an event

#

Doubt he uses on_error

slate swan
#
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?
arctic gyro
vale wing
slate swan
vale wing
#

Example

@bot.event
async def on_guild_join(guild):
    channel = guild.get_channel(123456789012345678)
    await channel.send(...)```
slate swan
#

ah

#

will I be able to send an embed message?

#

because im trying to make the bot send a message when it gets added

vocal snow
#

Sure, channel.send has an embed kwarg

#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
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**.
slate swan
#

Thank you! ๐Ÿ˜„

slate swan
#

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?

slate swan
slate swan
silver reef
#

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

sick birch
silver reef
#

what is setup_hook

pastel aspen
#

how can I mention ctx.member inside an embed?

silver reef
pastel aspen
#

oh it's .mention?

silver reef
#

ye

pastel aspen
#

thanks

#

this should work right?

silver reef
#

can u show the rest of the code for that command?

pastel aspen
#

probably is not working yet because I don't know how to convert the time to seconds

silver reef
#

yep that should works

pastel aspen
#

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

silver reef
#

int(object) / 60

#

u dont need a whole library for that

silver reef
pastel aspen
#

what

sick birch
slate swan
#

hey chat, why am i getting a strange error?

cannot import commands from discord.ext```
silver reef
#

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

slate swan
#

i doubt its the ide

silver reef
#

ik

#

maybe its an old python version or sth

#

i was canfused too

white aurora
#

from discord.ext import commands

slate swan
#

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 itlemon_imp

white aurora
#

lol

slate swan
#

i just want my bot to work xD

valid glacier
slate swan
#

i fixed it

#

reinstalled

pastel aspen
#

How can I ping a user in an embed?? I'm trying the code below but the embed looks like this

slate swan
#

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

pastel aspen
#

and does the ping inside the embed actually work?

#

or I need one outside?

slate swan
#

you can mention someone in the embeds description but it wont ping them

pastel aspen
#

okay, thanks

slate swan
#

@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

glad cradle
#

send a message together with an Embed

#

await ctx.send(ctx.author.mention, embed=embed)

slate swan
#

never said you cant but ok

glad cradle
#

๐Ÿ˜ถ

balmy bobcat
#

hello,
'Bot' object has no attribute 'preferences'

slate swan
#

read the error

balmy bobcat
#

I did, but isn't it supposed to have one?

slate swan
#

no?

balmy bobcat
#

I'm following a tutorial that uses client.preferences

#

oh well I thought there was one, my bad

slate swan
#

it's not like pip hid a method/property from you as a prank while installing

slate swan
#

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 todaypithink

#

only have a single bed owoSip

#

that has 2 sides

pastel aspen
#

do you sleep under your bed?

white aurora
#

grumpy humpty

silk fulcrum
#

top, bottom, left, right, front, back

cursive musk
#

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?

glossy flame
#

my bot is spamming after it detects keywords

slate swan
slate swan
#
file = discord.File("output.png")
embed = discord.Embed()
embed.set_thumbnail(url="attachment://output.png")
await ctx.send(file=file, embed=embed)

@cursive musk

cursive musk
#

thanks

slate swan
#

try something like that

cursive musk
#

i didnt know i could use attachment://output.png

slate swan
#

make sure the image is saved in the same directory as the bot

cursive musk
#

i have it in a folder from the same directory

#

./temp

slate swan
#

try it, and see what error you get ๐Ÿ‘€

cursive musk
#

i have a bad feeling about this

slate swan
#

it might work

cursive musk
#

alright i will respond if it doeesnt work

#

its not really responding an image @slate swan

slate swan
cursive musk
slate swan
#

why are you using .format, and is the folder named /temp?

cursive musk
#

it will save a new file

wicked atlas
# cursive musk

attachement:// references attachments to the message, not where they are on your computer

cursive musk
#
embed.set_thumbnail(url="attachment://output.png")
glossy flame
# slate swan we need to see some code..
@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.")```
cursive musk
cursive musk
wicked atlas
#

yes

cursive musk
#

do i have to get the obj tho?

wicked atlas
#

then you attach the file to the message, and then use ``attachment://filename` to access it

cursive musk
#

when i wont send it?

cursive musk
wicked atlas
#

It won't

#

try it

cursive musk
#

alright thanks i will try it

wicked atlas
cursive musk
#

this is not what i meant

wicked atlas
#

What code do you have?

slate swan
#

What code did you use

cursive musk
wicked atlas
#

temp/ is not part of the filename

cursive musk
#

i need to get it from a folder

#

called temp

wicked atlas
#

Yes, but when it's an attachment to your message, it's not in a folder

cursive musk
#

so {}gen.png?

wicked atlas
#

the attachment::// isn't referenceing the file on your computer

#

yes

slate swan
#

also you should probably use f strings instead of format, they're faster

cursive musk
#

okay i will do that then instead

#

of and what is the max width and height from a discord.Embed.image?

wicked atlas
#

I don't think there's a max size, discord just scales the image

slate swan
#

Yeah

wicked atlas
#

you can upload 4k images to discord but it'll look the same in the client as a 720p image (if it loads)

cursive musk
#

i mean like

#

the size of a picture

slate swan
cursive musk
#

like
width = 69
height = 120

#

what is the max?

slate swan
#

I am pretty sure discord will automatically scale it down if it's too big

cursive musk
#

oh

wicked atlas
#

Yeah, there's no max size specified anywhere

cursive musk
#

okay then

#

alright thanks guys

slate swan
#

๐Ÿ‘‹

glossy flame
#

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.")```
slate swan
#

Why are using & operator

#

that's for like bits

wicked atlas
glossy flame
#

thats not the problem

glossy flame
#

how do I prevent it?

wicked atlas
#

Add this if statement to the start of your handler

if message.author.bot:
    return
glossy flame
#

thank you my good man

wicked atlas
#

If the author of the message, is a bot, it will exit the function

glossy flame
#

I am such a fool

wicked atlas
#

And yeah, can tell you're coming from another language. In python, & is a bit operator. You might want and

wicked atlas
#

or not thats not logic ๐Ÿ’€

glossy flame
#

actually python is my first language

slate swan
#

๐Ÿ˜ญ

glossy flame
#

and someone reccomended me &

slate swan
#

Who..

glossy flame
#

for intersection

slate swan
#

๐Ÿคท

wicked atlas
#

yeah I didn't fully read

slate swan
#

I've never seen that operator used anywhere

glossy flame
#

ye I need the &

#

to check for common elements in both lists

wicked atlas
#

!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)
unkempt canyonBOT
#

@wicked atlas :white_check_mark: Your 3.11 eval job has completed with return code 0.

{'when'}
slate swan
#

Ohh

glossy flame
#

woah that is cool

slate swan
#

you can always use intersect as well lol

unkempt canyonBOT
#

@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'?
slate swan
wicked atlas
#

@glossy flame if you want to play around with the eval command, I'd suggest doing it in #bot-commands

glossy flame
#

Ok thank friend

wicked atlas
#

๐Ÿ‘

pastel aspen
white aurora
#

that's against tos

wicked atlas
#

It's only against TOS if you're using something like ytdl to download content from somewhere that dosen't allow it

white aurora
#

yes i'm aware

#

youtube tos5

pastel aspen
white aurora
#

what do you mean by music bot?

pastel aspen
#

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

white aurora
#

yes that is against youtube's terms of service

pastel aspen
#

how are there music playing bots then

wicked atlas
#

That's why Rythm and Groovy got taken down

pastel aspen
#

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

proud apex
#

How to make the buttons that were attached to the embed work after restarting the bot? discord_components

pastel aspen
sick birch
pastel aspen
sick birch
#

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

pastel aspen
#

one of the best features of discord bots was the music thing

#

youtube really likes to ruin stuff

pastel aspen
slate swan
timber dew
#

HI, What is the function to make the title of an embed and the description

#

help plz

slate swan
timber dew
#

thx

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

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...
slate swan
#

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?

slate swan
slate swan
#

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}")

slate swan
#

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

slate swan
#

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 โ€ข

slate swan
left raptor
#

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?

sick birch
#
@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

pliant gulch
#

voice_channel: None | discord.,VoiceChannel

sick birch
#

As the whole point is to get a concrete voice client regardless of it's status before

pliant gulch
#

The correct typehint is None | discord.VoiceChannel

sick birch
#

Oh I thought you were talking about voice_client

pliant gulch
#

Instead of using if and else

pastel aspen
#

can the .play() command play from urls?

slate swan
pastel aspen
#

on discord voice channel

slate swan
pastel aspen
#

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'
slate swan
#

yeah I can't help though

#

since it's against tos

pastel aspen
#

is there anywhere I can get help? jesus I just wanna play music for 1 server

slate swan
pastel aspen
#

is FFmpegPCMAudio against the tos?

slate swan
cold sonnet
#

automating download from youtube and spotify is

pliant gulch
#

Even if downloading was allowed you'd still have licensing issues

slate swan
#

Lf a basic currency bot in discord.py (sample code)

echo dock
#

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

sick birch
#

member: discord.Member

tired notch
#

does anyoe have good references for discord py 2.0 buttons

sick birch
unkempt canyonBOT
#

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.
sick birch
#

also there are plenty of examples in the official github under the /examples/views folder

tired notch
#

ok found it thanks

sick birch
#

That's the current syntax to typehint

slate swan
#

!typehint

unkempt canyonBOT
#

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.

slate swan
#

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

sick birch
slate swan
sick birch
#

!paste If it's long do it here, but if it's short, in this chat is fine

unkempt canyonBOT
#

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.

slate swan
#

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

sick birch
#

Could you paste everything inside settings.json?

slate swan
#

nooo that would leak my bot token and Captcha token

sick birch
#

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?

slate swan
#

{
"capmonsterKey": "",
"botToken": "",
"guildID": "",
"botAdminId": [
""

],
"botWhitelistedId": [
    ""
]

}

#

yea thats the setting.json it was working before

#

it says in the error that its in main.py

sick birch
#

just gonna code block it for ease

{
    "capmonsterKey": "",
    "botToken": "",
    "guildID": "",
    "botAdminId": [
        ""

    ],
    "botWhitelistedId": [
        ""
    ]
}
slate swan
#

so you want me to use this?

sick birch
#

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?

slate swan
#

just so i can screen share

sick birch
#

I would rather keep it here, sorry

#
    "botAdminId": [
        ""

    ],

is kind of strange to me, you're sure there's only 1 item in there?

slate swan
#

yea there is 1 item there

sick birch
#

And the extra space underneath it is there?

sick birch
slate swan
#

so its the settings.json?

sick birch
#

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

slate swan
#

nothings missing leme try to paste your new one you sent

sick birch
#

The one I sent was the same one you sent, I was just resending it so it had syntax highlighting

slate swan
#

ahhh so nothing is different about it?

sick birch
#

Nope

slate swan
#

Hmm so what do you think i can do to fix it

sick birch
#
    "botAdminId": [
        ""

    ],

is the extra space under the "" there in your file?

slate swan
#

cause everything in the settings.json file is the same as it was when the bot was working

broken citrus
#

hey guys, how do i let user input with a discord bot?

sick birch
#

Ah okay, can you re-send the JSON file exactly how it is, but with the important bits removed?

broken citrus
#

kinda like input("") but on discord

sick birch
unkempt canyonBOT
#

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**...
broken citrus
#

ty

slate swan
#

{
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
"",
],
"botWhitelistedId": [
"",
]
}

#

how do i send it like a code like you did robin

sick birch
#
{
    "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?

sick birch
#

plugging it into a JSON validator is always a good idea

north glade
#

how do i fix

slate swan
#

.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

sick birch
slate swan
slate swan
north glade
#

cry

#

i posted it in the wrong help section oh no

#

no need to be a dick

slate swan
#

!rule 5 and this, we don't help with self bots

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

north glade
#

lol petty asf

white aurora
#

relax

slate swan
#

its not really a self bot its a business bot ahaha

sick birch
#

@slate swan looks like you can't have trailing commas

slate swan
sick birch
#

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?
  ]
}
slate swan
#

OOooo i get it so like this maybe?

sick birch
#

This only applies to the last element, by the way

slate swan
#

{
"capmonsterKey": ""
"botToken": ""
"guildID": [ ""
""]
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}

#

so like that? see how there is none of these ,

sick birch
#
{
  "some list": [
    "item1", <---- need this since it's not the last one
    "item2" <----- no comma since last element
  ]
}
sick birch
slate swan
#

remSmile if you just want a bot config in other file you can use something like a yaml file or .env

sick birch
#

yaml โ‰๏ธ

slate swan
left raptor
#

I'm trying to just make it play audio in the voice channel from script

#

with no user input required

sick birch
#

Ah right didn't see that

left raptor
#

so I don't have access to ctx

sick birch
#

But you're way too much stuff in on_ready

slate swan
left raptor
#

so I just want a function?

#

and call that function

sick birch
slate swan
#

Robin could you type it in the correct format for me like these ,

#

also appreciate you for helping

sick birch
slate swan
sick birch
#

only the last items in a list can't have commas

sick birch
left raptor
#

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)```
sick birch
#

so basically

list = ["item1", "item2", "item3"]
                                 ^ no comma here (this is the trailing comma if there was)
left raptor
#

like this always returns None

discord.utils.get(bot.voice_clients, guild=guild)```
because bot.voice_clients returns None
slate swan
sick birch
#
list = ["item1", "item2", "item3", ]
                                 ^ โŒ
sick birch
slate swan
#

running it hopefully fixed it

left raptor
#

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

slate swan
#

ahhh it didn't fix it man i think im just breaking it even more this is frustrating

slate swan
sick birch
#

Well no, that was just an example

slate swan
#

are you sure its a settings.json issue?

sick birch
#

Yes

#

JSON hates trailing commas, vscode would usually tell you where it is but I'm guessing you aren't using it

slate swan
#

this must be such a simple fix to a good coder

#

nah im using uhh replix

sick birch
#

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

slate swan
sick birch
#
  "botAdminId": [
        "",
    ],
    "botWhitelistedId": [
        "",
    ]

i see 2 trailing commas here, which are the problem

slate swan
#

Yea but those have tokens and ids in them aren't they suppose to have trailing commas

sick birch
#

Regardless of what's in them, trailing commas are invalid JSON

#
  "botAdminId": [
        "", <---- needs to go โŒ
    ],
    "botWhitelistedId": [
        "", <---- needs to go โŒ
    ]
slate swan
#

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)

sick birch
#

Alright, could you send how it looks like now? With the important bits removed of course

#

!code

unkempt canyonBOT
#

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.

sick birch
#

Use json instead of py like:
```json
your code here
```

slate swan
#

{
"capmonsterKey": "",
"botToken": "",
"guildID": [ "",
""],
"botAdminId": [
""
],
"botWhitelistedId": [
""
]
}

sick birch
#

hmmm JSON validator is showing it as valid

#

Oh this is used.json

slate swan
#

so what does that mean

sick birch
#

This is an error in a different file, in used.json

slate swan
#

Nothing is inside of used.json lmao

sick birch
#

That's the problem

left raptor
#

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

sick birch
#

Empty JSON files need to have {}

sick birch
slate swan
#

so i put this inside of the empty used.json {}

left raptor
left raptor
slate swan
#

Bro even bigger error now wtf

sick birch
left raptor
#

how do I get the voice client without ctx

slate swan
sick birch
#

Let's see it

left raptor
#

cause this sure doesn't work

voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)```
slate swan
sick birch
sick birch
unkempt canyonBOT
#

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.

slate swan
left raptor
sick birch
#

And guild_id is the actual ID of a guild your bot is in?

left raptor
#

yes

sick birch
#

Where are you doing it, in on_ready?

left raptor
#

guild being server right

sick birch
#

Right

left raptor
sick birch
#

Temporarily banned

slate swan
sick birch
slate swan
sick birch
sick birch
#

The best way to not have this happen in the future is to not use replit, as it's usually the cause for it

slate swan
#

temporarily banned what does that even mean yoo

#

im banned for what?

sick birch
#

Means you can't use the API for a certain amount of time

slate swan
#

what do i have to create new?

sick birch
#

Nothing. Just wait it out, think it's about half an hour? not sure though

left raptor
#

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"))```
slate swan
sick birch
slate swan
#

Dam why do you think it did that

sick birch
#

Wait out the ban for now, and for it to not happen again stop using replit as it's honestly pretty bad

sick birch
slate swan
sick birch
#

You do

slate swan
#

whats a good website i can use like replit

slate swan
sick birch
#

VSCode, Pycharm, vim, emacs

sick birch
# slate swan How so?

Replit's machines are underpowered, so they can have a supercomputer and let potentially hundreds of people use it at once

slate swan
#

Godam

sick birch
#

Bottom line is you're not the only one using that replit host machine

slate swan
#

so vscode is a website or you talking about the app

sick birch
#

The app

slate swan
#

its a private one i paid for though

sick birch
#

Are you on the hacker plan?

slate swan
#

so nobody can access it

sick birch
#

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

slate swan
#

i know how to do it with replit though

sick birch
#

Oh no, for that you'll have to buy a VPS. VScode is just the editor

sick birch
slate swan
sick birch
#

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

sick birch
sick birch
slate swan
unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
loud shard
#

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

sick birch
slate swan
#

is this good or trash

loud shard
sick birch
slate swan
sick birch
#

But looking at the specs in a vacuum, it's pretty terrible lol

slate swan
#

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?

sick birch
#

Little bit yeah, but the other one will do for a pretty simple discord bot

#

They're not all that process intensive

slate swan
sick birch
#

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

slate swan
left raptor
sick birch
slate swan
slate swan
#

#discord-bot-hosting

sick birch
left raptor
slate swan
sick birch
# slate swan 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

slate swan
sick birch
#

"Cheaty" because subcommands are not meant as a "use spaces in your command free card"

sick birch
#

Yeah but.. not ideal

left raptor
#

like this?

voice_client = discord.Guild.voice_client()```
#

this makes an instance of the voice client class?

slate swan
sick birch
#

(it's not very difficult either)

paper sluice
left raptor
#

so how do I get an instance of a discord.Guild

paper sluice
#

Then fetch_guild

sick birch
#

Try fetching

guild = await bot.fetch_guild(guild_id)
left raptor
sick birch
#

Full traceback please?

left raptor
#
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'```
sick birch
#

Hmmm looks like something's awry with the internals

left raptor
#

bot isn't None, I just checked that

slate swan
left raptor
#

and the guild id is right

sick birch
#

No, bot.__session is None though for some reason

left raptor
#

oh

#

could it be because I keep running the script with the bot already in the voice channel

sick birch
#

And this is in your on_ready?

left raptor
#

since nothing in my code tells it to leave

left raptor
sick birch
#

Do you have the proper intents?

left raptor
sick birch
#

!intents

unkempt canyonBOT
#

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.

slate swan
#

@sick birch are you sure you would be able to help me over text 100% if i bought this vps

zealous jay
#

why do suddenly embeds look all streched?

sick birch
zealous jay
#

is there a way to avoid this?

sick birch
#

or just for testing purposes do discord.Intents.all()

slate swan
#

Can someone help me with this discord bot in a call

zealous jay
#

like they are always the maximum lenght

sick birch
left raptor
sick birch
#

The way discord embeds are shown are kind of strange to be honest

left raptor
#

with intents.guilds to true

zealous jay
#

that's sad, it looks terrible

sick birch
left raptor
sick birch
zealous jay
#

i guess haha

slate swan
#

@sick birch Bro my bot randomly started working lol

#

its up now

#

im not sure how but it is

left raptor
#

I don't see guild intents on my dashboard

#

you mean the developer portal right

left raptor