Why am I receiving this error?

ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/cogs/ActionCog.py", line 36, in on_message
    buffer = await self.client.database.buffer(message.author.id)
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/rpu_database.py", line 60, in buffer
    buffer = await self.db['buffer'].find_one({'user_id': user_id})
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/collection.py", line 1508, in find_one
    for result in cursor.limit(-1):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1262, in next
    if len(self.__data) or self._refresh():
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1153, in _refresh
    self.__session = self.__collection.database.client._ensure_session()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1868, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1811, in __start_session
    self._topology._check_implicit_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 583, in _check_implicit_session_support
    self._check_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 599, in _check_session_support
    self._select_servers_loop(
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 269, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: encoding with 'idna' codec failed (UnicodeError: label empty or too long), Timeout: 30s, Topology Description: <TopologyDescription id: 64f71a41ad1b5bfeb8bc78e4, topology_type: Unknown, servers: [<ServerDescription ('mongodb%2bsrv%3a%2f%2fhirukarogue%3adv%40plasma123%40rpucloudserver.bscpl0p.mongodb.net%2f%3fretrywrites%3dtrue%26w%3dmajority', 27017) server_type: Unknown, rtt: None, error=UnicodeError("encoding with 'idna' codec failed (UnicodeError: label empty or too long)")>]>
1 Like

its not finding what discord client means i would recommend defining what discord is

1 Like

strange, cus other coommands are working, but anything related to database don’t work

Traceback (most recent call last):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/cogs/ActionCog.py", line 24, in _annonymous_mode_switch
    anonimity = await ctx.bot.database.switch_anonimous_mode(ctx.author.id)
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/rpu_database.py", line 124, in switch_anonimous_mode
    checker = await self.db['anonimity'].find_one({'user_id':user_id})
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/collection.py", line 1508, in find_one
    for result in cursor.limit(-1):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1262, in next
    if len(self.__data) or self._refresh():
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1153, in _refresh
    self.__session = self.__collection.database.client._ensure_session()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1868, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1811, in __start_session
    self._topology._check_implicit_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 583, in _check_implicit_session_support
    self._check_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 599, in _check_session_support
    self._select_servers_loop(
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 269, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: encoding with 'idna' codec failed (UnicodeError: label empty or too long), Timeout: 30s, Topology Description: <TopologyDescription id: 64f72c63c4bf74f4152aea67, topology_type: Unknown, servers: [<ServerDescription ('mongodb%2bsrv%3a%2f%2fhirukarogue%3adv%40plasma123%40rpucloudserver.bscpl0p.mongodb.net%2f%3fretrywrites%3dtrue%26w%3dmajority', 27017) server_type: Unknown, rtt: None, error=UnicodeError("encoding with 'idna' codec failed (UnicodeError: label empty or too long)")>]>

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

Traceback (most recent call last):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/hybrid.py", line 442, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'switch' raised an exception: ServerSelectionTimeoutError: encoding with 'idna' codec failed (UnicodeError: label empty or too long), Timeout: 30s, Topology Description: <TopologyDescription id: 64f72c63c4bf74f4152aea67, topology_type: Unknown, servers: [<ServerDescription ('mongodb%2bsrv%3a%2f%2fhirukarogue%3adv%40plasma123%40rpucloudserver.bscpl0p.mongodb.net%2f%3fretrywrites%3dtrue%26w%3dmajority', 27017) server_type: Unknown, rtt: None, error=UnicodeError("encoding with 'idna' codec failed (UnicodeError: label empty or too long)")>]>

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

Traceback (most recent call last):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/hybrid.py", line 442, in _invoke_with_namespace
    value = await self._do_call(ctx, ctx.kwargs)  # type: ignore
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'switch' raised an exception: ServerSelectionTimeoutError: encoding with 'idna' codec failed (UnicodeError: label empty or too long), Timeout: 30s, Topology Description: <TopologyDescription id: 64f72c63c4bf74f4152aea67, topology_type: Unknown, servers: [<ServerDescription ('mongodb%2bsrv%3a%2f%2fhirukarogue%3adv%40plasma123%40rpucloudserver.bscpl0p.mongodb.net%2f%3fretrywrites%3dtrue%26w%3dmajority', 27017) server_type: Unknown, rtt: None, error=UnicodeError("encoding with 'idna' codec failed (UnicodeError: label empty or too long)")>]>

Like, why all that is related to database don’t work?

1 Like

you may need to define the databasa of discord because if you dont it doesnt know because when it tries to connect it doesnt normally have access

1 Like

well, i defined the database here:

import motor
import asyncio
import pymongo
import motor.motor_asyncio

class Database:
    def __init__(self) -> None:
        self.dev_client: motor.motor_asyncio.AsyncIOMotorClient | None = None

    async def connect(self, connection_uri: str, /) -> None:
        self.dev_client = motor.motor_asyncio.AsyncIOMotorClient(connection_uri)
        if self.dev_client is not None:
            self.db = self.dev_client['rpu_database_beta']
            print("Database connected!")
        else:
            self.db = None
            print("Cannot connect to Database!")

    async def close(self) -> None:
        self.dev_client.close()


    ### PREFIXES ###
    # this section is for prefixes

    # this function will create a new prefix for a guild
    async def set_prefix(self, *, guild_id: int, prefix: str) -> None:
        if await self.db['prefixes'].find_one({'guild_id':guild_id}) is None:
            await self.db['prefixes'].insert_one({
                'guild_id': guild_id,
                'prefix': prefix
            })
        else:
            await self.db['prefixes'].update_one({
                'guild_id': guild_id,
                'prefix': prefix
            })

    # this function will delete the prefix of a guild, reseting it to the standard one
    async def remove_prefix(self, *, guild_id: int) -> None:
        document = await self.db['prefixes'].find_one({'guild_id': guild_id})

        if document is not None:
            await self.db['prefixes'].delete_one({'guild_id': guild_id})

    # this function will grab the prefix of the bot in a guild, if there is none the prefix will be the default one
    async def get_prefix(self, *, guild_id: int) -> str | None:
        document = await self.db['prefixes'].find_one({'guild_id': guild_id})
        
        if document is not None:
            return document["prefix"]
        else:
            return None

    ### BUFFERS ###
    # This section is to help the bot on performance

    # This is a buffer initiator and associator
    async def buffer(self, user_id):
        buffer = await self.db['buffer'].find_one({'user_id': user_id})
        if buffer is None:
            await self.db['buffer'].insert_one({
                'user_id': user_id,
                'buffer': list()
            })
            buffer = await self.db['buffer'].find_one({'user_id': user_id})
        
        buffer = buffer['buffer']

        database = await self.db['characters'].find_one({'user_id': user_id})
        if database:
            char_list = database['characters']
            char_buffer = list()
            if len(buffer) > 0:
                for i in buffer:
                    char_buffer.append(char_list[i])

            return char_buffer
        else:
            return list()
    
    # this is a buff register
    async def buffer_reg(self, user_id, registry):
        buffer = await self.db['buffer'].find_one({'user_id': user_id})
        if buffer is None:
            buffer = await self.db.buffer.insert_one({
                'user_id': user_id,
                'buffer': list()
            })

        buffer = buffer["buffer"]
        database = await self.db['characters'].find_one({'user_id': user_id})
        char_list = database['characters']
        for num, i in enumerate(char_list):
            if i == registry:
                buffer.append(num)
                if len(buffer) > 10:
                    buffer.pop(0)
                break

        await self.db['buffer'].update_one({
            'user_id': user_id
        }, {'$set': {'buffer': buffer}})

    ### ANONIMITY ###
    # This is for those who wants to turns their actions anoomynously

    #anonimity
    async def anonimity_check(self, user_id):
        checker = await self.db['anonimity'].find_one({'user_id':user_id})
        if checker is None:
            await self.db['anonimity'].insert_one({
                'user_id': user_id,
                'anonimity': False
            })
            checker = await self.db['anonimity'].find_one({'user_id':user_id})
        
        checker = checker['anonimity']

        return checker
    
    #switch true or false anonymous mode
    async def switch_anonimous_mode(self, user_id):
        checker = await self.db['anonimity'].find_one({'user_id':user_id})
        
        switch = bool

        if checker is None:
            checker = await self.db['anonimity'].insert_one({
                'user_id': user_id,
                'anonimity': True
            })
        elif checker['anonimity']:
            switch = False
        else:
            switch = True

        await self.db['anonimity'].update_one({
            'user_id': user_id
        }, {'$set': {'anonimity': switch}})

        return switch

    ### WEBHOOK LOG ###
    # to keep track which webhook belongs to the log serves well

    #this function serves as a webhook tracker each time a new message is made
    async def webhook_log_reg(self, *, user_id: int, message_id: int):
        database = await self.db['webhook_log'].find_one({'user_id': user_id})
        if database is None:
            await self.db['webhook_log'].insert_one({
                'user_id': user_id,
                'webhook_log': list()
            })
            database = await self.db['webhook_log'].find_one({'user_id': user_id})
        
        message_list = database['webhook_log']

        message_list.append(message_id)
        if len(message_list) > 256:
            message_list.pop(0)
        
        await self.db['webhook_log'].update_one({
            'user_id': user_id
        }, {'$set': {'webhook_log': message_list}})

    async def webhook_log_confirm(self, *, user_id: int, message_id: int):
        database = await self.db['webhook_log'].find_one({'user_id': user_id})
        if database:
            message_list = database['webhook_log']
        else:
            return False

        if message_id in message_list:
            return True
        else:
            return False

    ### DEFAULT CHARACTERS ###
    # This is the standard version of creating characters, when you don't use templates you use default

    # This function will search docs using user ID, character name and/or prompt_prefix
    async def search_default_character(self, *, user_id: int, name: str | None = None, prompt_prefix: str | None = None) -> None:
        database = await self.db['characters'].find_one({'user_id': user_id})
        documents = list()
        if database:
            char_list = database['characters']
            if name and prompt_prefix:
                for i in char_list:
                    if name in i['name'] and prompt_prefix in i['prompt_prefix']:
                        documents.append(i)
            elif prompt_prefix:
                for i in char_list:
                    if prompt_prefix in i['prompt_prefix']:
                        documents.append(i)
            elif name:
                for i in char_list:
                    if name in i['name']:
                        documents.append(i)
            else:
                for i in char_list:
                    documents.append(i)
        
        return documents if len(documents) > 0 else None

    # this function will register the newly created character
    async def register_default_character(self, *, user_id: int, name: str, prompt_prefix: str, image: str | None = None) -> None:
        data = {
            'name': name,
            'prompt_prefix': prompt_prefix,
            'image_url': image
        }

        database = await self.db['characters'].find_one({'user_id': user_id})
        if not database:
            await self.db['characters'].insert_one({'user_id': user_id,
                                                    'characters': list()
                                                    })
            database = await self.db['characters'].find_one({'user_id': user_id})

        char_list = database['characters']
        if len(char_list) > 0:
            for i in char_list:
                if i['prompt_prefix'] == data['prompt_prefix']:
                    return "ERROR"            

        char_list.append(data)

        await self.db['characters'].update_one({'user_id': user_id}, {'$set': {'characters': char_list}})
    
    # this function will delete a character by name or prompt_prefix
    async def delete_default_character(self, *, user_id: int, name: str | None = None, prompt_prefix: str | None = None) -> None:
        database = await self.db['characters'].find_one({'user_id': user_id})
        
        if database:
            char_list = database['characters']

            instances = list()

            for num, i in enumerate(char_list):
                if name in i['name'] or prompt_prefix in i['prompt_prefix']:
                    instances.append(num)

            if len(instances) == 0:
                return "ERROR"
            elif len(instances) == 1:
                char_list.pop(instances[0])
                await self.db['characters'].update_one({'user_id': user_id}, {'$set': {'characters': char_list}})
                return "SUCESS"
            else:
                documents = list()
                for i in instances:
                    documents.append(char_list[i])
                return documents
        else:
            return "ERROR"

    # this function will update any stuffs related to the character
    async def update_default_character(self, *, user_id: int, old_name: str | None = None, old_prompt_prefix: str | None = None, new_name: str | None = None, new_prompt_prefix: str | None = None, new_image: str | None = None) -> None:
        database = self.db['characters'].find_one({'user_id': user_id})
        
        if database:
            char_list = database['characters']

            instances = list()

            for num, i in enumerate(char_list):
                if old_name in i['name'] or old_prompt_prefix in i['prompt_prefix']:
                    instances.append(num)

            if len(instances) == 0:
                return "ERROR"
            elif len(instances) == 1:
                document = char_list[instances[0]]
                if new_name:
                    document = {
                        'name': new_name,
                        'prompt_prefix': document['prompt_prefix'],
                        'image_url': document['image_url']
                    }
                    char_list[instances[0]] = document
                elif new_prompt_prefix:
                    document = {
                        'name': document['name'],
                        'prompt_prefix': new_prompt_prefix,
                        'image_url': document['image_url']
                    }
                    char_list[instances[0]] = document
                elif new_image:
                    document = {
                        'name': document['name'],
                        'prompt_prefix': document['prompt_prefix'],
                        'image_url': new_image
                    }
                    char_list[instances[0]] = document
                await self.db['characters'].update_one({'user_id': user_id}, {'$set': {'characters': char_list}})
                return "SUCESS"
            else:
                documents = list()
                for i in instances:
                    documents.append(char_list[i])
                return documents
        else:
            return "ERROR"

and here:

import bot_token
import discord
from discord import app_commands
import asyncio
from discord.ext import commands
import os
from rpu_database import Database
import os
from urllib import parse

bot_status = ["initializing", "active", "shutting down"]
DEFAULT_PREFIX = "rpu->"
EXTENSIONS = [
    'jishaku',
]
INTENTS = discord.Intents.default()
INTENTS.message_content = True


class Bot(commands.Bot):

  def __init__(self) -> None:
    super().__init__(
        intents=INTENTS,
        command_prefix=prefix_setup,
        case_insensitive=True,
    )
    self.database = Database()
    print("Bot Connected!")

  async def setup_hook(self) -> None:
    await self.database.connect(parse.quote_plus(os.environ['database']))
    self.db_loop = self.database.dev_client.get_io_loop()
    for extension in EXTENSIONS:
      await self.load_extension(extension)
    await self.add_cog(PrefixCog(self))
    for filename in os.listdir("./RP-Utilities-Beta/cogs"):
      if filename.endswith(".py"):
        await self.load_extension(f"cogs.{filename[:-3]}")
    guild = discord.Object(1135999359985647706)
    await self.tree.sync()

  async def close(self) -> None:
    await super().close()
    await self.database.close()


async def prefix_setup(bot, message):
  prefix = await bot.database.get_prefix(guild_id=message.guild.id)
  if prefix:
    return prefix
  else:
    return DEFAULT_PREFIX


class PrefixCog(commands.Cog):

  def __init__(self, bot: Bot) -> None:
    self.bot = bot

  @commands.hybrid_group(name="prefix",
                         fallback="help",
                         invoke_without_command=True)
  async def _prefix(self, ctx: commands.Context, *, prefix: str) -> None:
    await ctx.send(
        "Use this command to set or reset the this bot prefix in your server")

  @_prefix.command(name="set")
  async def _prefix_set(self, ctx: commands.Context, *, prefix: str) -> None:
    await self.bot.database.set_prefix(guild_id=ctx.guild.id, prefix=prefix)
    await ctx.send(f"Prefix set to `{prefix}`.")

  @_prefix.command(name="reset")
  async def _prefix_reset(self, ctx: commands.Context) -> None:
    await self.bot.database.remove_prefix(guild_id=ctx.guild.id)
    await ctx.send(f"The prefix has been reset to `{DEFAULT_PREFIX}`.")


Bot().run(bot_token.return_token())

But for some reason i still receive those erroers

1 Like

have you ever tried using a code checker website

1 Like

i never knew that this exists

1 Like

can you mark mine as solved now

1 Like

why, first i need to check the problem, i can’t say it’s not solved yet, limit of 10000 characters

1 Like

okay my code is too big to be analyzed

1 Like

i couldn’t solve my problem by using a checker since my code is too big

1 Like

how about you break it up into segments using it btw what the fortnite

1 Like

okay so, acording to the code verifier it couldn’t find any secure issues

1 Like

maybe it works or are you doing it in the wrong coding language

1 Like

Hello @HirukaRogue can you please share your repl?

1 Like

how do i do it? I have no idea how to share my repl

1 Like

Just follow this:

2 Likes

here:
https://replit.com/@HirukaRogue/RP-Utilities

1 Like

What’s the error you’re receiving?

1 Like

this:

ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/cogs/ActionCog.py", line 36, in on_message
    buffer = await self.client.database.buffer(message.author.id)
  File "/home/runner/RP-Utilities/RP-Utilities-Beta/rpu_database.py", line 60, in buffer
    buffer = await self.db['buffer'].find_one({'user_id': user_id})
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/collection.py", line 1508, in find_one
    for result in cursor.limit(-1):
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1262, in next
    if len(self.__data) or self._refresh():
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/cursor.py", line 1153, in _refresh
    self.__session = self.__collection.database.client._ensure_session()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1868, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1811, in __start_session
    self._topology._check_implicit_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 583, in _check_implicit_session_support
    self._check_session_support()
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 599, in _check_session_support
    self._select_servers_loop(
  File "/home/runner/RP-Utilities/.pythonlibs/lib/python3.10/site-packages/pymongo/topology.py", line 269, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: encoding with 'idna' codec failed (UnicodeError: label empty or too long), Timeout: 30s, Topology Description: <TopologyDescription id: 64f71a41ad1b5bfeb8bc78e4, topology_type: Unknown, servers: [<ServerDescription ('mongodb%2bsrv%3a%2f%2fhirukarogue%3adv%40plasma123%40rpucloudserver.bscpl0p.mongodb.net%2f%3fretrywrites%3dtrue%26w%3dmajority', 27017) server_type: Unknown, rtt: None, error=UnicodeError("encoding with 'idna' codec failed (UnicodeError: label empty or too long)")>]>

Anything that involves database always ends up being this error

1 Like