#๐Ÿ”’ mongo db help

55 messages ยท Page 1 of 1 (latest)

languid snow
#

MongoDB Connection Error: SSL handshake failed: ac-8xro1x8-shard-00-00.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),SSL handshake failed: ac-8xro1x8-shard-00-01.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),SSL handshake failed: ac-8xro1x8-shard-00-02.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 67fa42c63baaa36aedc87b0a, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-8xro1x8-shard-00-00.xracwhk.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-8xro1x8-shard-00-00.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('ac-8xro1x8-shard-00-01.xracwhk.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-8xro1x8-shard-00-01.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('ac-8xro1x8-shard-00-02.xracwhk.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-8xro1x8-shard-00-02.xracwhk.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]>

Getting this error when trying to use mongo db

zinc mantleBOT
#

@languid snow

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

meager portal
#

Configure it correctly to accept connections from an official MongoDB client first, or something lower tech than Python like curl or ssh. MongoDB has stacks of docs on how to do this.

manic robin
#

maybe your project doesnt have a specified IP address

#

to log in

languid snow
#

but now im getting error

manic robin
#

just use

#

!paste

zinc mantleBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

languid snow
#

this

#

thats my user id

#

heres the code

manic robin
languid snow
#

ik

manic robin
#

@languid snow

naive mason
#

Get rid of that try that's catching the error and then run the code again. You're hiding important information about the error by doing that.

manic robin
languid snow
languid snow
#
from pymongo import MongoClient
import certifi
import os

def get_mongodb_client():
    uri = os.getenv("URI")
    if not uri:
        raise ValueError("URI environment variable not set")
    return MongoClient(uri, tlsCAFile=certifi.where())

def load_json(file_path, default=None):
    if default is None:
        default = {}
    
    # Special handling for ranks.txt
    if file_path == "ranks.txt":
        with open(file_path, 'r') as f:
            import json
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return default
    
    # Handle points data from MongoDB
    client = get_mongodb_client()
    db = client.legiondatabase
    collection = db.points

    # Convert MongoDB documents to the expected format
    data = {}
    for doc in collection.find():
        user_id = doc.pop('_id')  # Use _id as user_id
        data[str(user_id)] = doc

    return data or default

def save_json(file_path, data):
    try:
        client = get_mongodb_client()
        db = client.legiondatabase
        collection = db.points

        # Convert data to MongoDB documents
        for user_id, user_data in data.items():
            collection.update_one(
                {'_id': user_id},
                {'$set': user_data},
                upsert=True,
                server_selection_timeout_ms=5000,  # 5 second timeout
                max_time_ms=5000
            )
    except Exception as e:
        print(f"MongoDB operation failed: {e}")
        # Fallback to file storage
        import json
        with open(file_path, 'w') as f:
            json.dump(data, f, indent=4)
manic robin
languid snow
#

yes

manic robin
#

screenshot there

manic robin
# languid snow yes

and btw, how can i run your bot. just want to test some things to replicate the error

languid snow
# manic robin and btw, how can i run your bot. just want to test some things to replicate the ...
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
from pymongo import MongoClient
import certifi

# Load environment variables
load_dotenv()

uri = os.getenv("URI")

client = MongoClient(uri, tlsCAFile=certifi.where())
print("Successfully connected to MongoDB database!")

# Initialize bot intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

# Initialize bot and database
client = commands.Bot(command_prefix="!", intents=intents, application_id=1353325444929294409)

async def load():
    print(f"Loading extensions...")
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            try:
                await client.load_extension(f"cogs.{filename[:-3]}")
                print(f"Loaded {filename}")
            except Exception as e:
                print(f"Failed to load {filename}: {e}")

@client.event
async def on_member_join(member):
    if not member.bot:
        join_channel = client.get_channel(879517540949303377)
        if join_channel:
            member_count = len([m for m in member.guild.members if not m.bot])
            join_embed = discord.Embed(
                title="Member Joined",
                color=0xD4AF37,
                timestamp=discord.utils.utcnow()
            )
            join_embed.set_author(name=member.name, icon_url=member.display_avatar.url)
            join_embed.add_field(name="Account Created", value=discord.utils.format_dt(member.created_at, style='R'), inline=True)
            join_embed.add_field(name="Invited By", value=inviter_info, inline=True)
            join_embed.add_field(name="Member", value=member.mention, inline=True)
            join_embed.add_field(name="Member Number", value=str(member_count), inline=True)
            join_embed.set_footer(text=f"User ID: {member.id}")

            await join_channel.send(embed=join_embed)

@client.event
async def on_ready():
    await load()
    await client.tree.sync(guild=discord.Object(id=879166421328871464))
    await client.change_presence(activity=discord.Game(name="Vivat Legio"))
    print(f"Logged in as {client.user.name}")

@client.event
async def on_raw_reaction_add(payload):
    if payload.channel_id != 1178851981842972772:
        return

    if str(payload.emoji) not in ["โœ…", "โŒ"]:
        return
    channel = client.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    user = await client.fetch_user(payload.user_id)

    protected_roles = ["Overseer", "Magister Divisionis", "Submagister legionis",  "Tribunus Laticlavius", "Tribunus", "Tribunus Cohortis", "Centurion Prior", "Centurion"]

    member = await channel.guild.fetch_member(user.id)
    user_roles = [role.name for role in member.roles]

    if any(role in protected_roles for role in user_roles):
        if str(payload.emoji) == "โœ…":
            await message.reply("Your clearance request has been accepted, please continue to follow event hosting format.")
        elif str(payload.emoji) == "โŒ":
            await message.reply("Your clearance has been denied.")

if __name__ == "__main__":
    token = os.getenv("TOKEN")
    if not token:
        raise ValueError("No token found in .env file")

    import time
    while True:
        try:
            client.run(token)
        except discord.errors.HTTPException as e:
            if e.status == 429:  # Rate limit error
                print("Rate limited. Waiting 60 seconds before retrying...")
                time.sleep(60)
                continue
            raise e
manic robin
#

can you just send all in a zip file

languid snow
weak ridge
#

I suggest using the asychronous version

#

-# Sqlite3 is even better!

manic robin
weak ridge
#

Well it depends 100%

But most of the time you are using relational database when working with Discord

manic robin
#

json is way easier and doesnt require to install the library

weak ridge
#

easier ain't always better

#

When working with relational db, sqlite is more suitable

manic robin
weak ridge
#

yes it is pretty fast and sqlite is local

manic robin
weak ridge
#

Yes, but what your expectation of fast can be different from mine

manic robin
weak ridge
#

up to you to decide which one you want to use

manic robin
naive mason
languid snow
zinc mantleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.