#discord-bots

1 messages · Page 1098 of 1

paper sluice
#

ya

#
color,string=getattr(discord.Color,['green','red'][(l:=random.randint(0,30))>20]),f"ok{'sus' * l}ok"
dusky pine
#

[True, False][[True, False](random.randint(0, 2) == 1)]

#

best rng imo

dim sentinel
#
 
@spi.command()
async def pp(ctx):
    size= random.randint(0, 9)
    color = None
    pp_string = f"8{'=' * size}D"
    if size> 5:
        embul=discord.Embed(title="PP calculator",color=discord.Color.red())
        embul.add_field(name=f"Your pp length\n{pp_string}",value="This is not a random response.")
        await ctx.channel.send(embed=embul)

    else:
        embul=discord.Embed(title="PP calculator",color=discord.Color.red())
        embul.add_field(name=f"Your pp length\n{pp_string}",value="This is not a random response.")
        await ctx.channel.send(embed=embul)
    ```
#

better?

dusky pine
#

looks good

dim sentinel
#

baaaaah

#

still not working

dusky pine
#

try using await ctx.reply instead of await ctx.channel.send

dim sentinel
slate swan
#

show

dusky pine
dusky pine
dim sentinel
#

afterwards i did

dusky pine
#

ok

dim sentinel
#

but still doesnt work

slate swan
#

oh you ment the embed color and not a red line as a syntax error🗿

sullen pewter
#
class Verification(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label='Verify', style=discord.ButtonStyle.green)
    async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        name = 'Verified'
        member = interaction.user
        role = interaction.guild.get_role(member.guild.roles, name=name)
        await member.add_roles(member, role)
        await interaction.response.send_message(embed = discord.Embed(f"Welcome! {interaction.user.name}, you have been granted {role.name} role!", color = discord.Colour.green))

        self.value = True
        self.stop()```
Does anyone know why it can't find a role
dim sentinel
#

it should show red

#

if it above something

#

it should show green

#

i wanted it to be like that

dusky pine
#

try removing the color = None line, it's useless in this case

vocal snow
dim sentinel
dim sentinel
#

it shows green for 5

#

but shows red for 6

slate swan
#

at what length should it show green or red

dim sentinel
sullen pewter
#

interesting

dim sentinel
#

red

#

else

slate swan
#

so red if more than 5 =s?

dim sentinel
#

green

dusky pine
#

try flipping that mouth to the side

dim sentinel
dusky pine
#

> to <

dim sentinel
slate swan
dim sentinel
#

it's actually working

#

but why is it working

slate swan
#

your logic was incorrect

#

5> x means, 5 is greater than x

dim sentinel
#

oh dear lord

#

you are correct

#

sorry for this thing

slate swan
#

its ok, quite common mistake.

dim sentinel
#

i should just go to elementary school 🤡

dusky pine
#

now the only thing you should change is that lie in the description

dim sentinel
#

again @dusky pine THANK YOU SO MUCH

dusky pine
#

np

dusky pine
#

This is not a random response.
😂

dim sentinel
#

no

#

it remains ✨

#

all of my commands has

#

This is a random response.

#

but not for this one ;)

devout iris
#

How to clone a channel?

slate swan
unkempt canyonBOT
#

await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Clones this channel. This creates a channel with the same properties as this channel.

You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to do this.

New in version 1.1.
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

paper sluice
#
async def no_callback(interaction):

      await user.send('Offer Declined!')
    

      TCEmbed2 = nextcord.Embed(
        title="Offer Declined!",
        description=f"{user.mention} `{user}` has declined the offer to join the {emoji}{team.mention}\n > **Coach:** {interaction.user.mention} `{interaction.user}`\n > **Roster:** `{len([member for member in team.members])}/25`"
      )
      embed.set_author(name="PFG Transactions", icon_url=guildurl)
      embed.set_thumbnail(url=emoji.url)
      embed.timestamp = datetime.datetime.utcnow()

      await TChannel.send(embed=TCEmbed2)
      await e.delete()
      

      yes.callback = yes_callback
      no.callback = no_callback

u set the callbacks inside the this function, so it doesn't get set at all

#

outside no_callback

#

and so send it with ur embed you would do

view = View() # check docs for proper imports
view.add_item(yes)
view.add_item(no)
ctx.send(embed=embed, view=view)
shrewd apex
#

wdym?

dapper stirrup
#

?

loud junco
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
dapper stirrup
#

thx

loud junco
#

Np

#

U can just try printing them tbh

dapper stirrup
#

sec

loud junco
#

str(x) tho

dapper stirrup
#

" Represents a Discord user"

will it mention me? or just my nickname

loud junco
#

Go ahead and try?

loud junco
#

If u want name just go await ctx.send(ctx.author.name)

dapper stirrup
visual island
#

no

#

User.mention

loud junco
dapper stirrup
#

da?

#

Oh

loud junco
#

I mean User.mention

#

Wrong reply

dapper stirrup
#

thx, I got it

loud junco
#

Thanks @visual island 😂😂😂

dapper stirrup
#

da

grizzled lake
#

Hey guys, i got an error that on_reaction_add works only for client.user not other users

#

There's a code

loud junco
#

!d discord.Member

dapper stirrup
#

also I have to learn English cause my A -1 isn't good enough

grizzled lake
#

uh

slate swan
grizzled lake
#

wait

#

i got an idea

#

oh nvm

slate swan
regal pulsar
#

bot = commands.Bot(intents=intents)

grizzled lake
#

yeah i was thinking about it right now and when i passed i got a new issue
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

#

so

regal pulsar
#

go to the developer portal

slate swan
#

!intents read what it says about the dev portal

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.

regal pulsar
#

enable the intents that you need

slate swan
#

😳 amoled theme on discord desktop is cool

grizzled lake
#

got it

#

ill test right now

#

yoo thanks, it's working

#

!close

#

oops

slate swan
grizzled lake
#

wrong channel xD

slate swan
#

Is there a downside having a intent enabled that you dont us

yes, discord.py will cache the unwanted objects related to that intents too

#

for the 2nd part of the question, .all() intents includes previlaged intents too.

slate swan
#

^

slate swan
#

meh.

#

can someone help me idk if it’s to do with discord bht ansi text does not show up on my@iphone it just shows the colour code then the text which looks very ugly is there anyway i can change that but keep the colours?

heady sluice
odd mango
#

i do

    def format_command_help(self, no, command):
        signature = self.helpcommand.get_command_signature(command)
        docs = self.helpcommand.get_command_brief(command)
        return f"{no}. {signature} - {docs}"```
i dont have a seperate function for get_command_signature
i want to do something like this without having to make a seperate function 
```py
    def get_command_signature(self, command):
        return '**%s%s** `%s`' % (self.clean_prefix, command.qualified_name, command.signature)```
any clue how?
heavy folio
#

why cant you use get_command_signature
you wanna customize it or

odd mango
#

yeah

#

i wanna customize it

heavy folio
#

override get_command_signature

slate swan
odd mango
#

i am doing format_command_help in a different class

regal pulsar
#

hmm

slate swan
#

what class does it come from?

warped mirage
#
bedem = discord.Embed(name="unmute", description=f"{member.mention} has successfully been unmuted!", color=0xBFFF00)
TypeError: Embed.__init__() got an unexpected keyword argument 'name'```
#

any ideas ?

brave moth
#

im trying to make a daily command with sqlite3 and if someone is claiming first time and the date is not found, the date should be recorded included the daily reward because i added 'none' but i keep getting the nonetype error

slate swan
#

its title

warped mirage
slate swan
warped mirage
#

title? since when tf

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.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
slate swan
warped mirage
#

nah ... i always used name=

brave moth
# slate swan could you show some code.

heres the error:

    if str(claimed[0]) == 'None':
TypeError: 'NoneType' object is not subscriptable

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable```
slate swan
warped mirage
#

idk

slate swan
brave moth
# slate swan claimed variable is None here, may i see how is it defined.

heres the partial code:

claimed=db.execute(f"SELECT claimed_date FROM bankData WHERE user_id = {ctx.user.id}").fetchone()  
if str(claimed[0]) == None:
  #give coins for first time claimers
elif (date.today() - date.fromisoformat(str(claimed[0]))).days > 0:
  #give coins to people already in the db
else:
 #already claimed. wait for tomorrow```
plain inlet
#

i need to create a discord bot for my own server, that can perform a certain task by taking information from my own website. I'll give a simple example....like you go onto my website and enter your discord ID and the bot automatically DM's you "hello" [considering u're already in my server as well]. Is this functionality even possible?

slate swan
slate swan
plain inlet
slate swan
plain inlet
#

no

#

im pretty new to everything

#

in python too i just know basics like loops and lists, etc

brave moth
slate swan
#

imagine installing notepad++ when you got notepad

plain inlet
#

notepad cannot run the programs for python or other languages

#

notepad++ can

slate swan
plain inlet
paper sluice
#

wait u can run code from notepad++? i thought it was just syntax highlighting

plain inlet
slate swan
plain inlet
shrewd apex
#

dosent like notepad only open the code in text format? in its raw encoding?

slate swan
plain inlet
brave moth
#

im using notepad++ for now to edit the py files bcoz vsc in my pc is not working

paper sluice
brave moth
#

it opens for 1 minute then crashes

plain inlet
#

i use python IDLE

shrewd apex
#

hmm not the best ide ig...

shrewd apex
#

right click and open with notepad works too...

paper sluice
shrewd apex
#

eval(input ())💀

maiden fable
#

Uhh, might wanna take it to an OT channel

plain inlet
#

okay

plain inlet
shrewd apex
#

nothing wrong just don't like using it

plain inlet
paper sluice
# plain inlet whats wrong

its dangerous, you are basically evaluating python expressions, so i can write stuff you damage your files and it will run that

shrewd apex
#

for inputing list?

#

i just use normal input most of the time when i need like raw input from terminal then parse the string

paper sluice
#

if you want to take a list as input, you can use json.loads or input().split() depending on the type of input

plain inlet
#

i dont know what is json

#

i just started using python

#

i only know the very basics

paper sluice
#

ah, then dont worry about it. you will learn it when you have to.

shrewd apex
#

i mean for basic school hw and stuff eval(input()) is standard

#

so u need not worry

plain inlet
#

can you suggest me any resource when i can start learning discord bot programming from scratch

plain inlet
paper sluice
shrewd apex
paper sluice
#

if you don't know oop, async-programming etc, even the best resources will not be of any help

plain inlet
#

basically im at school level python [basics, loops, fucntions, lists, etc] and i wanna work my way upto making my own discord bot that serves the purpose i mentioned

paper sluice
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

livid hinge
#

its quite unusual to see someone not jumping in head first to the deep end lol

shrewd apex
#

quite a few people i met in help channels jumped into tkinter/pygame without basics

livid hinge
#

and like facial recignition lmao

shrewd apex
#

opencv💀

livid hinge
#

exactly 🤣

#

maybe decorators, async

shrewd apex
livid hinge
#

idk if classes are a must at first, but would be good to learn

shrewd apex
#

yeah

livid hinge
shrewd apex
#

nice i used to play on Nintendo wii

livid hinge
#

i prob need to get a wii u at some point

shrewd apex
#

nice 😊

livid hinge
#

that is real # of members?

#

pretty impressive

#

nice

quaint epoch
#

you got it right

cloud dawn
#

watching 15925 members is pretty sus

livid hinge
slate swan
#

*my bot has 15... members in its cache

livid hinge
#

like overseeing to 15k members 😄

#

the fact is that bots see all

slate swan
#

if they have member intents, yes
i have a bot with 3-4k users in its mutual servers but only 20 of them are cached caused i disabled the member intent

slate swan
#

help me pls

#
@tree.command(name = 'ping', description='veja o meu ping')
async def ping(interaction : discord.Interaction):
    embedVar = discord.Embed(title="Ping", description=f"Meu ping : {client.latency} ms")
    await interaction.response.send_message(embed=embedVar)
quaint epoch
slate swan
#

i need bot ping

quaint epoch
#

do print(str(client.latency))

#

oh wait

slate swan
quaint epoch
#

maybe call it, i dunno if that will work

#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
slate swan
quaint epoch
#

bruh

#

okay try client.latency()

#

i dunno why it isn't working

#

also try print(type(client))

placid verge
# slate swan

Try this

await ctx.send(f'Pong! In {round(client.latency * 1000)}ms')
slate swan
placid verge
#

oh you are using interaction

slate swan
#

that's why i put it in embed

slate swan
placid verge
#
embedVar = discord.Embed(title="Ping", description=f"Meu ping : {round(client.latency * 1000)} ms")
slate swan
#

discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: TypeError: unsupported operand type(s) for *: 'property' and 'int'

placid verge
slate swan
#
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()
            self.synced = True
        await self.change_presence(status=discord.Status.dnd, activity=discord.Game('Meu dev : Francisco Araújo#4576'))
        print(f"Entramos como {self.user}.") 


aclient = client()
tree = app_commands.CommandTree(aclient)

placid verge
slate swan
#

because my bot works with slash commands

shrewd apex
#

client.latency()*1000

quaint epoch
#

bruh

slate swan
quaint epoch
slate swan
#

but latency is supposed to return a string

#

is a lib bug?

quaint epoch
slate swan
#

yhe yhe

#

a problem with a ping command

lyric apex
slate swan
silk mauve
#

discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed

#

Can someone help

slate swan
scarlet aurora
#
    @commands.command()
    async def roast(self, ctx, user: discord.Member):
        r = requests.get("https://insult.mattbas.org/api/insult")
        json_data = json.loads(r.text)
        roast = json_data[0]

        await ctx.send(roast)```

How can I call the insult if it has nothing to call it by using requests?
shrewd apex
#

requests is sync use aiohttp

scarlet aurora
#

oh alright

shrewd apex
#

u can just send the res.text

scarlet aurora
#

that don't work

shrewd apex
#

y?

scarlet aurora
#
Traceback (most recent call last):
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\llVll\Desktop\Projects\TMG Bot .git\cogs\utils.py", line 143, in roast
    roast = json.loads(r.text)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\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)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
shrewd apex
#

await ctx.send(res.text)

scarlet aurora
#

oh

#

so I don't need the json.load ?

#

alright, it works, thanks a lot

slate temple
#

do discord bots count as web applications

quaint epoch
shrewd apex
shrewd apex
lyric apex
#
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.description: Must be 4096 or fewer in length.```
#

How to show embed description that can come like i want to show the things that come in 4096 length

#

And like x emojis more?

#

Like this?

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
strange vessel
#

No error comes up in the console but when i type one of these words nothing happens the code is

#

``@client.event
async def on_mesage(msg):

if msg.author != client.user:
    for text in bad_stuff:
        if "Bypass" not in str(msg.author.roles) and text in str(msg.content.lower()):
          await msg.delete()``
chrome latch
#

hey anyone have idea how to design my inventory database

#

like how do i store user, items user have and all that in database

#

how many tables i will need

#

what datatype to store stuff

#

thanks

sick birch
#

Relational?

chrome latch
#

i don't have much experience with databases

sick birch
#

Are you using a relational database or NoSQL?

chrome latch
#

i know foregin keys and all

chrome latch
sick birch
#

The data model varies greatly between those 2

#

Ah, relational then

chrome latch
#

yep

sick birch
#

The first thing I can think of is a table with 3 columns: some unique ID, a user ID, and a singular item

#

The user IDs will repeat

#

One row is for each item the user has

#

So when you select that users ID, you get all of their items

chrome latch
#

well my approach was

#

i will create two tables 1 for user and 1 for items

#

now i will give some unique id to items

#

user table will have user_id as primary key and a items string

sick birch
#

And the 2nd table is a mapping of item IDs to items?

chrome latch
sick birch
#

Ah I see where you’re getting it

chrome latch
#

so i can fetch the user and split the items

sick birch
#

That’s a viable strategy

chrome latch
#

then convert them into int and fetch the item

sick birch
#

But usually I like to not mix a bunch of data in one column

chrome latch
sick birch
#

In a database it really shouldn’t matter

chrome latch
#

oh

sick birch
#

They’re meant to handle large amounts of rows

#

And be very fast while they’re at it

chrome latch
sick birch
#

Yeah you can also do joins in this case

#

Use the item ID in users table as a foreign key

chrome latch
sick birch
#

Join the users and items table

chrome latch
#

@sick birch but as i will need one user table for other kind of info like wallet and all

#

should i create a table inventory to store inventory of all users

sick birch
#

Yes keep your tables scoped properly

chrome latch
#

and connect user_id with user table (foregin key)

#

and item_id with item table (foregin key)

sick birch
#

That sounds good if you need the other data

#

If you only need inventory data just join users and items table

chrome latch
lyric apex
slate swan
#

0

chrome latch
#

like loop through roles and add there length to a varable

#

when variable leangth exceed

#

break the loop and add footer with "total - looped roles left!"

shell wing
#
    @setup.command()
    @commands.has_permissions(manage_guild = True)
    async def channel(ctx, channel:discord.TextChannel):
      async with selfbot.db.cursor() as cursor:
        await cursor.execute("SELECT channel FROM starSetup WHERE guild =?", (ctx.guild.id,))
        channelDATA = await cursor.fetchone()
        if channelDATA :
          channelDATA = channelDATA[0]
          if channelDATA == channel.id:
            return await ctx.send("That channel is already setup!")
          await cursor.execute("UPDATE starSetup SET channel = ? WHERE guild = ?", (channel.id, ctx.guild.id))
          await ctx.send(f"{channel.mention} is now a starboard channel!")
        else:
          await cursor.execute("INESERT INTO starSetup VALUES (?,?,?)", (5, channel.id, ctx.guild.id,))
          await ctx.send(f"{channel.mention} is now a starboard channel!")
        await selfbot.db.commit()
``` Error :- `Callback for setup command is missing "ctx" parameter.`
fading marlin
shell wing
#

there is ctx

fading marlin
#

you're missing self

shell wing
#

😭 alr

fading marlin
#

you're in a cog, which goes inside a class, which requires 'self' as its first parameter

shell wing
#

yups done now idk how i missed it

lyric apex
shell wing
#

code py if ctx.invoked_subcommand is none: return await ctx.send("That subcommand does not exist!")
error ```py
if ctx.invoked_subcommand is none:
NameError: name 'none' is not defined

chrome latch
#

@lyric apex

chrome latch
# chrome latch <@680994218977787927>

!e ```py
roles = ['cool', 'pro', 'dame', 'epic', 'amazing']
maxLength = 10
length = 0
idx = 0
for role in roles:
if length < maxLength:
length += len(role)
#other stuff
print(str(role), end=", ")
idx += 1
print(f"{len(roles) - idx} more roles")

unkempt canyonBOT
#

@chrome latch :white_check_mark: Your eval job has completed with return code 0.

cool, pro, dame, 2 more roles
shell wing
chrome latch
#

isinstance(ctx.invoked_subcommand, None)

#

try this instead of ctx.invoked_subcommand == None

shell wing
#
@commands.group()
    async def setup(self, ctx):
      if ctx.invoked_subcommand is None:
        return await ctx.send("That subcommand does not exist!")
#

this is the code though

fading marlin
#

traceback?

chrome latch
#

yes

shell wing
# fading marlin traceback?
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1342, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'none' is not defined
pliant gulch
#

!e ```py
max_length: int = 10
roles = [i for i in range(100)]

print(roles[:max_length])

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
fading marlin
pliant gulch
#

Then afterwards, join and append "more roles" etc

pliant gulch
#

Or am I wrong\

chrome latch
#

like if there are role with only 1 char each

#

then you can fit more then 10 tho

shell wing
# fading marlin above that it should say `The above exception was the direct cause of the follow...

its says this now :-

Ignoring exception in command setup channel:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/new-server/starboard.py", line 22, in channel
    async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1348, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'
fading marlin
#

you're not setting a bot var named 'db'

shell wing
fading marlin
#

I'm guessing you're using bot vars? and apparently you're trying to access one before you specify it

shell wing
#

by following a video...by glowstick on starboard

fading marlin
#

well you gotta assign your db thingamajig to bot.db

shell wing
#
setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))``` ??
fading marlin
#

same way you'd define any other variable self.bot.db = ...

#

you just gotta make sure you do that before you start calling any methods of it

shell wing
# fading marlin same way you'd define any other variable `self.bot.db = ...`
@commands.Cog.listener()
    async def on_ready():
      self.bot.db = starboard.db
      setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))
      await asyncio.sleep(2)
      async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS starsetup (starlimit INTEGER, channel INTEGER, guild INTEGER)")
      await self.bot.db.commit()
``` like this ?
fading marlin
#

you don't have to use setattr, and yes

shell wing
#

alr tyy

fading marlin
#

on a side note, you generally don't want to do stuff in on_ready

shell wing
#

oo okok

shell wing
#

do u mind joining the replit ?

fading marlin
fading marlin
#

but you're not using self there, and you're not defining bot anywhere else

pliant gulch
shell wing
# fading marlin but you're not using `self` there, and you're not defining `bot` anywhere else
 def __init__(self, bot):
        self.bot = bot

 @commands.Cog.listener()
    async def on_ready():
      self.bot.db = starboard.db
      setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))
      await asyncio.sleep(2)
      async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS starsetup (starlimit INTEGER, channel INTEGER, guild INTEGER)")
      await self.bot.db.commit()
shell wing
fading marlin
pliant gulch
#

!e ```py
roles = ["abc", "efg", "hij", "lmn"]
max_length = 10

print("".join([roles[i] for i in range(len(roles)) if sum(map(len, roles[:i])) < max_length]))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

abcefghijlmn
chrome latch
fading marlin
chrome latch
#

your code is write but as he is a beginner i was giving code which self explains

shell wing
fading marlin
#

2 more lines below

shell wing
#

bot.cursor...

fading marlin
#

there ya go

shell wing
#

so i make it all as bot.db ?

#

or self.bot.db ?

#

its in a cog

fading marlin
shell wing
#

alr

chrome latch
#

¯_(ツ)_/¯

#

my bad

shell wing
# fading marlin precisely
Ignoring exception in command setup channel:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/new-server/starboard.py", line 23, in channel
    async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1348, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'
#

ive literally changed it all to self.bot.db

fading marlin
#

did you remove the setattr?

shell wing
#

i remove the whole line of setattr ?

fading marlin
#

yeah

shell wing
slate swan
#

anyone?

fading marlin
fading marlin
shell wing
fading marlin
#

do you still have that piece of code in an on_ready event?

slate swan
#

how to add cooldown on event like on_reaction_add

fading marlin
#

you can't add cooldowns to events

shell wing
slate swan
#

@fading marlin can u help me to block multiple ticket in my code

#

because i dont have any idea how can i block it

fading marlin
#

use buttons instead of reactions

slate swan
#

@bot.event async def on_reaction_add(reaction, user): if '**🚀 ┇ SUPPORT**\n\n ► If you have any question\n ► If you need any help\n ► Open ticket with reaction on this message\n\n ╭ Spamming in ticket is disabled\n ┊ Ghost ping in ticket is disabled\n ┊ Multiple tickets are not allowed\n ╰ Opening for no reason is disabled' in reaction.message.embeds[0].description and reaction.emoji == '👾' and not user.bot: role = discord.utils.get(user.guild.roles, name="@everyone") chan = await user.guild.create_text_channel(name=f'ticket - {user}') await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False) await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True) embed = discord.Embed(description="**🚀 ┇ SUPPORT**\n\n ► Thanks for open ticket\n ► Now wait for a response from owners") embed.set_footer(text="†  Creator Matija#4633 † ") msg = await chan.send(embed=embed)

fading marlin
slate swan
fading marlin
#

save the id of the user that reacted to the message, and then check if the ID is on the list of users where you're storing tickets

slate swan
#

if u have time

shell wing
fading marlin
fading marlin
slate swan
# fading marlin then your on_ready is probably not being called

File "/root/trinity/a.py", line 101
if 'SUPPORT\n\nTo create a ticket react with ������' in reaction.message.embeds[0].description and reaction.emoji == '������' and not user.bot:
^^
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte

#

u can help?

fading marlin
#

������ is probably what's causing your issue

slate swan
fading marlin
#

replace it with \U0001f47e

#

or \👾

slate swan
#

👾

#

\U0001f47e

#

\👾

fading marlin
#

?

slate swan
fading marlin
#

hi?

slate swan
#

yo

#

I don't know what causes this error on windows the script works but when I want to run it on rasberry pi this error pops up

hardy wing
#

is amazon web services or google cloud better to host a discord bot on

full lily
#

what is users?

#

there's no "bank" key for him inside of users

#

make sure to give that key when the member joins your server

strange vessel
kindred epoch
strange vessel
#

oh so i just add import before it?

sick birch
strange vessel
#

Oh thx no error message comes up now but theres something wrong with my code when o try activate it nothing happens and theirs no error

#

its a purge commands btw

@client.command(aliases=['purge']) async def clear(ctx, amount=11): amount = amount+1 if amount > 101: await ctx.send('Cant delete more then 100 messages') else: await ctx.channel.purge(limit=amount) await ctx.send('Cleared Messages')

shrewd apex
#

u have intents enabled?

#

and intents= discord.Intents.all()

#

json data with key user id has no key named bank

round knoll
#

somehow the bot is stuck on a loop of removing the LIVE role. can someone verify this please?

sick birch
#

If you remove a role, it triggers the event, which removes a role, triggers event again, you get the point

shrewd apex
#

did u just jump headfirst into discord bots without knowing basic python?

maiden fable
#

In short, its like recursion

shrewd apex
#

or a while loop...

maiden fable
#

Or that, yea

shrewd apex
#

json stores just like a dict so u can make a key the same way as u would in a dict

round knoll
#

alright, a bit of revision, would this be good

maiden fable
#

Nice

sick panther
#

hi, hi, I just got a small problem, what's the right name for the permission "manage server"?
I wrote it like this:

@commands.has_permissions(manage_server=True)
maiden fable
#

manage_guild

sick panther
#

Oh, alright, I should've known that, ty

solemn igloo
#

what was the command to install a git library with pip
pip install git+U or something

maiden fable
#

pip install git+https://github.com/Rapptz/discord.py

solemn igloo
#

ok

slate temple
maiden fable
slate temple
#

so just outdated

maiden fable
#

Yes

slate temple
#

welp, alternatively I can just always make my own pagination utils embedded within my own bot file

solemn igloo
#
TypeError: timeout() got some positional-only arguments passed as keyword arguments: 'until'
solemn igloo
maiden fable
#

What

maiden fable
round knoll
# sick birch If you remove a role, it triggers the event, which removes a role, triggers even...

does this provide a better way of handling the role?

@bot.event
async def on_member_update(before, after):
    print("Zeddy bot is checking for roles")
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if LIVE_ROLE_ID in after._roles:
            return
            
        else:
            print("Giving LIVE Role")
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))

    else:
        if LIVE_ROLE_ID in after._roles: 
            print("Removing LIVE Role")
            await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
solemn igloo
solemn igloo
#

TypeError: timeout() got an unexpected keyword argument 'time'

sick birch
#

Because say something else changed (e.g they got a new role. and their activity hasn't changed), it's going to put you into a loop again

solemn igloo
#

there is no such argument

sick birch
#

Check if before they don't have an activity, but they have it after, instead of just checking if they have it after

#

that way you don't lock yourself into a loop

round knoll
#

this is complex.. im kinda lost lmao

sick birch
#

Yeah the logic is a bit complex, think it out first before writing out your code

#

Might be helpful to come up with psuedocode first

solemn igloo
#
TypeError: timeout() got some positional-only arguments passed as keyword arguments: 'until'```
#

its still happening

round knoll
#

so if the bot finds the activity called streaming, check if he has the live role, if he has, just return, else (if he does not and he his streaming) give him the role... if the person isnt streaming, and does not have the role, then return (just do nothing cause it's fine) if he is not streaming, and he has the role, remove the role

@bot.event
async def on_member_update(before, after):
    print("Zeddy bot is checking for roles")
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if LIVE_ROLE_ID in after._roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))

    else:
        if LIVE_ROLE_ID not in after._roles:
            return
        if LIVE_ROLE_ID in after._roles:
            print("Removing LIVE Role")
            await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
#

nope he still does not give me the role when im live.. and if i manually give myself the role, HE REMOVES IT!!

#

lol

vale wing
#

And yeah you need to get the role object by ID and then check if it is in list eg

live_role = after.guild.get_role(LIVE_ROLE_ID)
if live_role in after.roles:
    ...```
round knoll
#

ok let me try to fix it

round knoll
# vale wing Why using `_roles`, it is a protected member, there's normal `roles` attribute
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846


@bot.event
async def on_member_update(before, after):
    live_role = after.guild.get_role(LIVE_ROLE_ID)
    print("Zeddy bot is checking for roles")
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if live_role in after.roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))

    else:
        if live_role not in after.roles:
            return
        if live_role in after.roles:
            print("Removing LIVE Role")
            await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
vale wing
#

Also your any is wrong

#

It must be like this

any(a.type == discord.ActivityType.streaming for a in after.activities)```
#

Cause it checks if any of conditions from the given sequence is True

#

So basically you gotta form a sequence of bool values

dapper stirrup
#

no way, it's perfect

pale turtle
#

Sorry wrong place

round knoll
#

i fixed the any()

vale wing
# round knoll duplicate code?

after.guild.get_role(LIVE_ROLE_ID) in add_roles and remove_roles can be replaced with live_role as you have already defined it

vale wing
dapper stirrup
mossy jacinth
#

Hey is it possible for a modal, to have the Server invite of the Current server as placeholder? Nextcord

round knoll
#
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846


@bot.event
async def on_member_update(before, after):
    live_role = after.guild.get_role(LIVE_ROLE_ID)
    print("Zeddy bot is checking for roles")
    if any(a.type == discord.ActivityType.streaming for a in after.activities):
        if live_role in after.roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(live_role)

    else:
        if live_role not in after.roles:
            return
        if live_role in after.roles:
            print("Removing LIVE Role")
            await after.remove_roles(live_role)
#

alright, i got what you mean. i had trouble with the bot removing roles and not giving them too

vale wing
slate swan
#

thank you for that info!

round knoll
vale wing
#

Ok

round knoll
# vale wing Ok

i got my print (checking for roles) but it did not give me the LIVE role

vale wing
#

Try printing after.activities

round knoll
#

it's removing the role also, if i try to give it manually

vale wing
#

If they are empty

  1. If you have dpy 2.0 you need to listen for different event, iirc it is on_presence_update
  2. Make sure you have presence intent enabled
vale wing
round knoll
#

i think im on 1.8 or something, cause i used pip install

vale wing
# round knoll

all() includes all intents, you don't need to intents.members = True just an advice

vale wing
round knoll
#

ok, removed the intents = true

round knoll
#

i dont get the checking for roles

vale wing
#

I need you to print(after.activities) and you clearly haven't done that

round knoll
#

moved the print under the after.activities

#

oh sorry

vale wing
#

Do that at the very top of event

round knoll
#

where do you need the print?

#

before @bot.event?

vale wing
#

At the beginning of your function

#

after is inaccessible from outside of it

slate swan
#

Is there a way to get timeout action from the guild audit logs

slate swan
#

There is member_update but i really dont know lmao

vale wing
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
round knoll
vale wing
round knoll
#

got another one

(<Activity type=<ActivityType.playing: 0> name='Terraria' url=None details=None application_id=356943499456937984 session_id=None emoji=None>, <Spotify title='Trapped in Memories' artist='StreamBeats by Harris Heller' track_id='3tsEqC1nDukjBqlrVkC3RE'>)
Zeddy bot is checking for roles
vale wing
round knoll
#

im live nothing happening

vale wing
#

Does it get displayed in activities list

slate swan
#

!d disnake.AuditLogAction.member_update

unkempt canyonBOT
#

A member has updated. This triggers in the following situations:

• A nickname was changed

• They were server muted or deafened (or it was undone)

• They were timed out

When this is the action, the type of target is the Member or User who got updated...

round knoll
#

again if i give myself the LIVE role, the bot removes it

vale wing
#

"Triggers in the following situations: ... They were timed out"

vale wing
#

You may avoid that thing by adding a condition that would check if activities exclusively were updated

vale wing
#

2.0 is alpha and is installable only directly from git

#

It is not on pypi

round knoll
#

ah

round knoll
#

i tried this, and im getting (<Streaming name='prime and destroyer down.. Terraria shenanigans and deaths.. but mostly deaths || [!hello][!subgoals][!deaths][!cmd]'>

# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846


@bot.event
async def on_member_update(before, after):
    print(after.activities)
    live_role = after.guild.get_role(LIVE_ROLE_ID)
    print("Zeddy bot is checking for roles")
    if any(a.type == discord.Streaming for a in after.activities):
        if live_role in after.roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(live_role)

    else:
        if live_role not in after.roles:
            return
        if live_role in after.roles:
            print("Removing LIVE Role")
            await after.remove_roles(live_role)
slate swan
round knoll
abstract kindle
#

Possible to change bots pfp with code?

maiden fable
#

!d discord.ClientUser.edit

unkempt canyonBOT
#

await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the current profile of the client.

Note

To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") is given through the use of `fp.read()`.

The only image formats supported for uploading is JPEG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
maiden fable
#

bot.user returns an instance of ClientUser

round knoll
#

can someone help me fix this please, discord.py is stuck on 1.7 cause i used pip install

# checks if discord activity is streaming, if true, assign LIVE role, if False, remove LIVE role
LIVE_ROLE_ID = 983061320133922846


@bot.event
async def on_member_update(before, after):
    print(after.activities)
    live_role = after.guild.get_role(LIVE_ROLE_ID)
    print("Zeddy bot is checking for roles")
    if discord.Streaming in after.activities:
        if live_role in after.roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(live_role)

    else:
        if live_role not in after.roles:
            return
        if live_role in after.roles:
            print("Removing LIVE Role")
            await after.remove_roles(live_role)
abstract kindle
#

What are the rules on asking for help with hosting bots lol

#

I'm writing some code for a friend, but idk what service to recommend to her to host the bot

#

Cause I sure ain't hosting it

slate swan
misty stream
#

i am trying to create a text channel where the ctx member can edit the permissions this is my code

overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False , manage_channels=True),
        member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
        }
        channelnamelow=channelname.lower()
        channel = await guild.create_text_channel(channelnamelow, overwrites=overwrites , category=category )
        channel = await guild.create_voice_channel(channelnamelow, overwrites=overwrites , category=category)

what am i doing wrong ?

#

so basicly i can do !create test and it will create a text and voice chat called test
but i also want to be able to edit the permissions or invite other people in how do i do that

#

for now i am trying to be able to edit permissions of those channels

placid verge
misty stream
#

allright ill try that

placid verge
#

btw u should use manage_channel instead of manage_channels

misty stream
#

let me try that

misty stream
#

thats what it says

misty stream
#

let me tell my goal basicly i want to do !create test and it will create a text and voice channel in a catagory where members can invite other members

#

with !invite @ membername

#

but the invite thing didnt work at all

#

so i am now trying to make it so that people can add members by editing the channel permissions

#

but its still not working 😂

placid verge
misty stream
#

i tried that i copied over the permissions from there but still no luck :/

round knoll
#

alright the bot looks fixed now.. that was annoying lol

dim sentinel
#
spi.sniped_messages= {}

@spi.event
async def on_message_delete(message):
    spi.sniped_messages[message.guild.id] = (message.content,message.author,message.channel.name,message.created_at)

@spi.command()
async def snipe(ctx):
    contents,author,channel_name,time= spi.sniped_messages[ctx.guild.id]
    channel = ctx.channel
    try:
        embed=discord.Embed(description=contents, color=discord.Color.green(),timestamp=time)
        embed.set_author(name=f"{author.name}#{author.discriminator}",icon_url=author.avatar_url)
        embed.set_footer(text=(f"Deleted in: #{channel_name}"))
        await ctx.channel.send(embed=embed)
    except:
        embud=discord.Embed(title="Snipe not found",color=discord.Color.red())
        embud.add_field(name="There's nothing to snipe!",value="L")
        await ctx.channel.send(embed=embud)
``` the except part doesnt work help
round knoll
#

heres the fixed (for now?) code

# checks if discord activity is streaming, if true, assign LIVE role, if False, remove LIVE role
LIVE_ROLE_ID = 983061320133922846


@bot.event
async def on_member_update(before, after):
    live_role = after.guild.get_role(LIVE_ROLE_ID)
    print("Zeddy bot is checking for roles")
    if any(a.type == discord.ActivityType.streaming for a in after.activities):
        if live_role in after.roles:
            return
        else:
            print("Giving LIVE Role")
            await after.add_roles(live_role)

    else:
        if live_role not in after.roles:
            return
        if live_role in after.roles:
            print("Removing LIVE Role")
            await after.remove_roles(live_role)
#

maybe, but trying to make the code cleaner is what broke it in the first place

slate swan
#

apart from the print statements

#

oh mb

strange vessel
#

why does it say that ;-;

vale wing
#

isinstance(i, discord.ActivityType.streaming) will never be True because i is an instance of discord.Activity and discord.ActivityType is an enum

slate swan
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
#

not a screenshot

vale wing
#

Also why use replit 😳

strange vessel
#

mobile ;-;

stone beacon
strange vessel
#

i did

stone beacon
#

Cool

slate swan
#

Hello. please help me

wicked atlas
#

your code is alive

slate swan
#

and why error

wicked atlas
#

What error?

slate swan
#

My bot, worked for 2 days without any problems.

#

And now he going offline

#

when i click (Run)

wicked atlas
#

Well, you're gonna need to scroll up a bit in console there. All thats shown there is some html, nothing useful.

slate swan
#

seems like a cloudfare ban

wicked atlas
#

yeah was about to say that

slate swan
#

you would need to kill your container

wicked atlas
#

the IP your replit was running on probably got blocked 💀

slate swan
#

kill 1

wicked atlas
#

Yeah, this is one of the reasons you shouldn't use replit to host discord bots

wicked atlas
#

because the IP your bot uses when running off of replit is shared. With who knows how many other people, who may also be running discord bots. If one of those bots gets api banned or the IP gets blocked by cloudflare, then yours gets blocked as well. Usually a dedicated VPS is the way to go for hosting a bot

slate swan
#

i have hosting

sick birch
slate swan
#

uptimerobot and better uptime

sick birch
#

Uptimerobot is not a host

#

It's a monitoring tool to see if your websites stay up

#

better uptime is similar

wicked atlas
sick birch
elfin moon
#

I have this:

#

wheree do i put the URL

#

for the button

slate swan
elfin moon
wicked atlas
elfin moon
#

bruh i just use sparked host

slate swan
elfin moon
#

it's like only $1 per month

wicked atlas
#

You're never going to find a free (and reliable) hosting or VPS service. And if it is free, there is always some kind of catch.

sick birch
slate swan
#
  • thanks @sick birch
#
  • Thanks @wicked atlas
#

-Thanks @slate swan

#

pleasure

pliant gulch
#

me when hosting my first bot using a leftover server from my workplace

slate swan
#

how can i make this

#

when someone joins a VC the bot joins it

sick birch
#

Find the channel using the after voice state, join that

#

should be very easy

brave flint
#

does background task block main code?

#

my task all are asynchronous btw, but always get the application doesnt responds when the background task running

storm verge
#

anyone know some js

slate swan
#
    with open("emails.txt", "r") as file:
        lines = file.readlines()

    chosen_index = random.randrange(0, len(lines))
    chosen_line = lines[chosen_index]

    with open("emails.txt", "w") as file:
        del lines[chosen_index]
        file.writelines(lines)

    return chosen_line

    line = pop_random_line2()
    pyautogui.typewrite(line)```
#

how do make that work?

sick birch
slate swan
sick birch
slate swan
dusky pine
#

.topic exists here i didnt know

lament depotBOT
#
**What's one feature you wish more developers had in their bots?**

Suggest more topics here!

dusky pine
#

and it's customized for this channel

dusky pine
#

and please stop capitalizing embed titles like

Are You Sure?

#

Are you sure? looks better

abstract kindle
#

Hey guys, I'm trying to run my bot script on my raspberry pi but I think I messed up some of the packages or something

#

If anyone can help, that would be great! please ping me

minor totem
#

Hey I finished reworking my tutorial for interaction bots using Wumpy. I think there's some regulars here who might have something to say? Feedback is encouraged, even on stuff like the theme (although I know that it isn't perfect; I am trying lemon_sweat) and screenshots!

https://wumpy.readthedocs.io/ (if on mobile, open with Desktop mode)

pliant gulch
abstract kindle
#

Same

pliant gulch
#

Both in portait and landscape mode

abstract kindle
#

Reader mode works nicely though 😄

pliant gulch
minor totem
#

I haven't really specialized it for mobile yet. It should be readable if you set it as Desktop site?

minor totem
pliant gulch
#

Actually, relatively the mobile version is much more appeasing then what the desktop version renders currently

#

Kek

#

Oh never mind, I scrolled over and everything broke

minor totem
#

Yeah umm.. ignore the table of contents, you can't see it anyways 🙈

#

Ah shit I really need to work on the mobile stuff. Getting things together has been somewhat painfully and I imagine it doesn't get better 😅

brave flint
#

io taskses

sick birch
#

And you're sure none of them is blocking?

#

It doesn't matter if the function is async

#

Nothing inside of it needs to be blocking

#

Well actually to be more precise, nothing that takes a relatively long time should be blocking

brave flint
slate swan
#

can you send the code for the task

brave flint
#

hmm

sick birch
#

Because if nothing inside is blocking then something else is wrong

brave flint
#
@tasks.loop(seconds=150)
async def r_task(type):
    urlist = RADB().webhook_url(type)
    for i in ecchilist:
        embed = await RedditAuto().redditembed(i)
        if len(embed) >0:
            async with aiohttp.ClientSession() as session:
                embeds = embed["embeds"]
                ids = embed["ids"]
                for i in embeds:
                    for url in urlist:
                        webhook = Webhook.from_url(url, session=session)
                        await webhook.send(embed=i)
                    await RADB().addsended(ids[0])
                    ids.pop(0)```
#
    def webhook_url(self, type):
        urls = []
        for i in self.RedditAutomationDB.find({type:"true"}):
            urls.append(i[f"{type}_url"])
        return urls```
slate swan
#

yeah, blocking mongodb driver

brave flint
slate swan
#

!pip motor :> or use run_in_executor

unkempt canyonBOT
brave flint
#

i think thats the problem but when i search "is mongodb threadsafe" it shown yes

brave flint
slate swan
#

ggs

brave flint
#

thx for ur help

brave flint
shrewd apex
#

pymongo?

slate swan
#

yeah they were using that ig

shrewd apex
#

ic

slate swan
#
for i in self.RedditAutomationDB.find({type:"true"})``` based on this
slate swan
#

looli i have my cs exams in 2hrs aaaaa

shrewd apex
#

yeah i saw the reddit was a bit misleading

shrewd apex
brave flint
slate swan
#

yeah, the reddit part is async, you're using asyncpraw right?

slate swan
brave flint
#

uh is there any motor docs?

slate swan
#

indeed, just google for "motor readthedocs"

brave flint
#

eh wait

#

so its just collabin motor and pymongo?

slate swan
#

its quite similar to pymongo tho~

shrewd apex
#

ik i saw 12 syllabus

#

network chapter requires some rote memorization

brave flint
shrewd apex
#

MySQL the only confusing part is multiple joins doubt they will go that deep into joins tho

brave flint
slate swan
shrewd apex
#

no joins?👀

#

ic

slate swan
#

tbh they dont even ask for constraints in exams, they just give you some tables and ask you to peform search/write operations on them

shrewd apex
#

constraints which the checks and parameter for creating tables right?

#

do they give foreign keys would slightly interesting if they did that 👀

slate swan
#

yep, CHECK, NOT NULL , etc

shrewd apex
#

nice

#

intresting part is if u use foreign key in same line as column name SQL parses but doesn't enforce

#

so u have to do

foreign key Id references tablea(id)
#

ATB sarth ace it 🎉

slate swan
#

thanks, ill go study now

slate swan
#

i need to revise the networks and communication chapter, too much theory to learn

shrewd apex
#

yeah

#

lots of stuff there

vocal snow
brave flint
#

the first internet on the world

slate swan
#

hey i have like 2 buttons with some condition the issue is that when 2 ppl click on the buttons together it runs the last check part 2 times
code:
https://paste.pythondiscord.com/ifuvorebip

the who_win function did 2 times

stray carbon
#
class Split(nextcord.ui.Button):
    def __init___(self):
        super().__init__(label="Split", style=nextcord.ButtonStyle.blurple, custom_id="Split_P2")

    async def callback(self, interaction):
        return # random shit here


class SplitOrSteal(nextcord.ui.View):
    def __init__(self, ctx, player: nextcord.Member, opponent: nextcord.Member):
        self.player = player
        self.opponent = opponent
        self._ctx = ctx
        self.player_choice: str = None
        self.opponent_choice: str = None
        self.player_clicked = False
        self.opponent_clicked = False
        super().__init__(timeout=180)
    
    @nextcord.ui.button(
        label="Split",
        style=nextcord.ButtonStyle.green,
        custom_id="Split_P1"
    )
    async def _callback(self, button, interaction):
        if interaction.user == self.opponent:
            return await interaction.response.send_message('This is not your turn!', ephemral=True)
        if interaction.user != self.player:
            return await interaction.response.send_message('This is not your game!', ephemral=True)

        for x in self.children:
            self.remove_item(x)
        item = Split()
        self.add_item(item=item)
        self.player_choice = "Split"
        self.player_clicked = True

        await interaction.response.edit_message(content='{self.player} has choosen, its {self.opponent}\'s turn.', view=self)

neat field
#

Then make it run so that only the user who initiated the command can only make the buttons works @slate swan

stray carbon
#

it sends some HTTPException, label is required

stray carbon
#

why does it say so :hmm:

neat field
#

Oh then make sure that whoever presses the button it’s there turn

#

Or just wait for one user at a time

slate swan
#

um

#

okay ill make them turn by turn

neat field
#

Cool 😎 I think it would be better for your code that way or wateve ur making

slate swan
#

Trying to add a role twice does not remove the role, right?

neat field
#

Why would u do that anyways

slate swan
#

Iterating through a list of members who "applied" for the role didn't get it.

neat field
#

Ah makes sense then why not add a check in it

#

So for eg
Members = []
for m in Members: If m.user.role == role.id: Something Else: Something

slate swan
#

I didn't think it would be of any use apart from making the code a bit slower but then I remembered reading something in the docs where running the same thing twice basically inverts the values. I think it was actually in discord.py and for app_settings.

neat field
#

Never heard of that but u could be write , and I don’t think adding that check will slow down to ur code at all

#

It’s processes at fast speed so u don’t rly need to worry bout that

slate swan
#

But the list is thousands of members long lol. Like you have to retrieve the channel history first and then retrieve the member info and then add role in them if they exist, Anyway, the process is done now. Thanks for your time!

neat field
#

Ye makes no difference

#

Trust me , I have something like that that iterates through 10of thousand of user id, and isn’t slow but it’s rly up 2 u

#

Just make sure your code is neat

#

Or just remove users from that list who already have the role

#

What’s the issue?

#

Try if role.name is not in team:

#

Are you checking the users role?

#

Whos role u checking if it’s in that list?

#

I can’t rly help since I don’t rly know the attributes that nextcord use

#

But if I’m not mistaken from what u said , just get a list of the author role and then check if in the team

#

If that’s not what u mean , ur code doesn’t make sense to what u said

#

Oof I got to go to schoool rn , hope it makes sense or if I couldn’t help then I’m sorry @slate swan

maiden fable
#

if role.name not in teams

slate swan
#
from discord.ext import commands

bot = commands.AutoShardedBot(command_prefix='!')

@bot.event
async def on_voice_state_update(member, before, after):
    if not before.channel and after.channel and member.id == 974780999936397352:
        await member.voice.channel.connect()  # Connect to the channel```
slate swan
torn sail
#

Yes

maiden fable
#

The channel do be kinda inactive today since no questions being asked

placid skiff
#

Don't worry, I'm back

#

Oh F***

#

I need to find a way to reprogram the proximity sensor of my phone

short silo
#
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: I/O operation on closed file

any idea what might be causing this.

placid skiff
#

Code?

little ether
short silo
little ether
short silo
vale wing
#

"Command raised an exception"

short silo
vale wing
#

Can you like give only that command's code

#

Like I am not going to scroll through all that

short silo
#

pretty out in the open

#

else

#
@bot.slash_command(guild_ids=config.Guild, description="Report a bug.")
async def bug_report(ctx):
 
    async def Dropdown_callback(interaction):
        value = Dropdown.values[0]
        embed = Embed(
            title=f"You selected {value} bug.",
            color=Colour.blue()
        )
        await Original_Interaction.edit_original_message(embed=embed, view=None)
        modal = Feedback(Value=value)
        await interaction.response.send_modal(modal)
 
    Dropdown.callback = Dropdown_callback
    view = View(Dropdown)
    Original_Interaction = await ctx.response.send_message(view=view, ephemeral=True)
vale wing
#

I don't think this is what causing that error

#

Also you should really look at PEP 8

#

!pep 8

unkempt canyonBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

little ether
#

looks like a func that deals with files

vale wing
#

And yeah I also recommend splitting your code into several modules

#

Having everything in one file is a very bad idea

short silo
#

oh wait

placid skiff
#

Hello everybody and welcome back to another episode of "Developing a discord bot in d.py without knowing python"

vale wing
#

and subclass the views for god's sake

placid skiff
#

Nope don't worry, it's just a meme here

short silo
placid skiff
#

The truth is rude

vale wing
#

Unnecessary autoremove remove 😳

short silo
#

i'll be out then, better figure it myself rather than asking for help here.

placid skiff
#

We could help you if you would send the block of code where your error raises

short silo
# placid skiff We could help you if you would send the block of code where your error raises

https://pastebin.com/yMhXTsnk

Main Function

@bot.slash_command(guild_ids=config.Guild, description="Check Equipment Information.")
async def equipment_info(ctx):
    # Making Views/Options
    First_menu_view = discord.ui.View()
    Second_menu_view = discord.ui.View()
    Third_menu_view = discord.ui.View()
    # Making Screen 1 buttons.
    button1 = Button(label="Army", custom_id="Army",
                     style=discord.ButtonStyle.green)
    button2 = Button(label="Navy", custom_id="Navy",
                     style=discord.ButtonStyle.green)
    button3 = Button(label="Air", custom_id="Air",
                     style=discord.ButtonStyle.green)
    button4 = Button(label="General", custom_id="General",
                     style=discord.ButtonStyle.green)
    # Making Screen 2 buttons.
    button5 = Button(label="Gold Equipments", custom_id="Gold",
                     style=discord.ButtonStyle.green)
    button6 = Button(label="Purple Equipments",
                     custom_id="Purple", style=discord.ButtonStyle.green)
    button7 = Button(label="Blue Equipments", custom_id="Blue",
                     style=discord.ButtonStyle.green)
    button8 = Button(label="Green Equipments", custom_id="Green",
                     style=discord.ButtonStyle.green)
    button9 = Button(label="Grey Equipments", custom_id="Grey",
                     style=discord.ButtonStyle.green)
    back_to_first_button = Button(label="<- Back")
placid skiff
#

Nice, the whole code D_D

short silo
#

sent*

vale wing
#

Damn

#

So many buttons

slate swan
#

views

vale wing
#

Could be easily simplified with for loop + array

slate swan
vale wing
#

Tuple of tuples is ok too ig

placid skiff
#

mhhh first of all you should not name variables Type or any other python builtin functions/methods

#

Yeah that is what would happen

vale wing
#
buttons_data = (("Button1", "custom_id1"), ("Button2", "custom_id2"))  # actually you need the custom ids only if you have persistent views
for name, custom_id in buttons_data:
    view.add_item(Button(label=name, custom_id=custom_id, style=discord.ButtonStyle.green))```
#

Dict might look cleaner tho I agree

slate swan
#

and a View subclass would be better in case

vale wing
#

Totally

placid skiff
#

Teach him how to

#

I'm takin a coffee lmao

slate swan
short silo
#

i am just learning so, I did find view subclass and stuff but didnt want to jump into it right away.

placid skiff
vale wing
vale wing
short silo
#

but anything on I/O error ?

shrewd apex
#

hello👋

#

what io?

short silo
vale wing
#

Ok

placid skiff
#

Send the full traceback when you're done

slate swan
slate swan
# short silo Let me fix the whole thing and i will be back.

if the file is already closed, you cant perform any actions to it, these are the cases

file = open("uwu.txt")
file.read()
file.close()
file.write("uwu") #This raises the same error as the file being closed

''' or '''

with open("uwu.txt") as file:
     file.read()
file.write("uwu") #This raises the same te error as the file being closed```
#

sarth otw to correct me

#

in short, you need to perform all those operations inside the context manager itself

slate swan
short silo
shrewd apex
slate swan
shrewd apex
#

so after linking my git acc to jetBrains site i just download the professional ide?

mossy jacinth
#

Can someone explain?

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

shrewd apex
#

😔 sigh ic

slate swan
slate swan
slate swan
shrewd apex
#

thx for helping🎉

maiden fable
#

U also get access to Fleet 👀

shrewd apex
#

does the old pycharm get auto uninstall or do i have to do it manually?

shrewd apex
maiden fable
slate swan
vocal snow
#

how did CS go sarth 👀

maiden fable
#

Ah, yes

slate swan
shrewd apex
vocal snow
#

set 4 didnt have too many network questions thankfully

shrewd apex
#

yeah

vocal snow
#

bliss

shrewd apex
#

most answers were in the questions itself

slate swan
shrewd apex
#

lmao i learned them all except i have a bit of trouble with multiple joins

slate swan
shrewd apex
#

so it's fine to have pycharm community and pro at same time?

shrewd apex
#

my friend got set-4 too

slate swan
#

i think everyone did

shrewd apex
#

prolly yeah

mossy jacinth
shrewd apex
#

i mean i saw there was two questions barely tricky one was group by and natural join one asked output and other the statement

slate swan
slate swan
#

linter wont raise an error on runtime

shrewd apex
#

oh runtime didn't see

mossy jacinth
shrewd apex
#

when u run a file normally it will show in terminal running from file path blah blah venv stuff

#

are u running the correct venv?

mossy jacinth
slate swan
#

i should be is not an answer

#

!venv see the highlighted text

unkempt canyonBOT
#

Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

shrewd apex
slate swan
#

im not sure, but with professional maybe yeah

shrewd apex
#

it says no valid license associated

shrewd apex
#

ic u have to req license

slate swan
#

for plugins?

shrewd apex
#

no u have to req for education license in and apply for it in jet brains website

slate swan
#

not really. lets shift to an ot channel and talk about it.

shrewd apex
#

ok

minor totem
#

I am just gonna send this again because I imagine there's different people online right now. I have reworked my Tutorial a bit for interactions bot with my library. If you have the time, check it out and let me know what you think!

The docs don't render nicely on mobile, use desktop if possible: https://wumpy.readthedocs.io/

slate swan
#

really looks great, but i think that it would be a bit more cleaner if the Topic header would be seperated from the contents, like here if it would be like
Tutorial

Getting Set Up
Creating Commands
...

that may look cleaner

#

as for the actual content, the implementation is very clean, especially the Option constructor

shrewd apex
#

looks nice but it would looks a bit better if these index

Tutorial
Getting Set Up
Creating Commands
Command Options
Option Choices
Context menus

were a bit more spaced and slightly bigger

minor totem
#

Thank you both! I fully agree, I need to add some indentation and spacing. The other pages should be indented underneath Tutorial

shrewd apex
#

np glad to be of help🙂

abstract kindle
#

hey guys

#

I know I can use ssh to run code on my raspberry pi

#

but I can't close the powershell window, or else the script will end, right?

#

How would I run my code on the raspberry pi 24/7? Also, would I have to hook it back up to a monitor if I wanted to rerun the script?

#

Is there any way run the code on the raspberry pi using ssh, rather than running the script on the powershell on my PC?

#

please @ if you respond lol

slate swan
#

hi im sending a view with a msg so how do i get the msg object in that view

msg = await ctx.send(...,view=someview())

i want msg in the view

#
view = discord.ui.View()

view.message = await send(..., view = view)
``` you can now access the message from the view using view.message / self.view inside the view class.
minor totem
#

There's option choices for that. No idea how to define it in different libraries

slate swan
# slate swan ```py view = discord.ui.View() view.message = await send(..., view = view) ``` ...
        a = rps(self.bot,firstperson=firstperson,firstpersonscore=firstpersonscore,secondperson=secondperson,secondpersonscore=secondpersonscore,match=match+1,toatalmatches=toatalmatches,ctx=interaction)
        s = disnake.Embed(title=f"{firstperson.name}'s chance",description=f"Match {match+1}/{toatalmatches}",color=aqua)
        a.msg = await interaction.send(f"{firstperson.mention},{secondperson.mention}",embed=s,view=a)
#view parame
(self ,bot: commands.Bot,firstperson : disnake.Member , firstpersonscore : int,secondperson : disnake.Member , secondpersonscore : int, match : int,toatalmatches : int,ctx : commands.Context, msg = None)

am i doing something wrong ?
it print None when i print it ...

#

if that a slash command?

#

yes, thats not how it works

#

..

slate swan
#

!d disnake.Interaction.edit_original_message use this :V

unkempt canyonBOT
#

await edit_original_message(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original, previously sent interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionMessage.edit "disnake.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.

Note

If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the message’s attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).