pymongo.errors.ConfigurationError: A DNS label is empty - database

I'm making discord bot with python. I was making leveling system using database (https://account.mongodb.com/) and I got this syntax error: pymongo.errors.ConfigurationError: A DNS label is empty. Please help me.
main.py:
import os
import discord
import datetime
import levelsys
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
cogs = [levelsys]
for i in range(len(cogs)):
cogs[i].setup(bot)
# Setting permissions that a user should have to execute this command.
print('Server Running')
bot.run(os.getenv('token'))
levelsys.py:
import discord
from discord.ext import commands
from pymongo import MongoClient
import urllib.parse
bot_channel = 798127930295058442
talk_channels = [690995360834912327]
level = ['new', 'old_new', 'Master Oogway']
levelnum = [5, 15, 30]
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
cluster = MongoClient("mongodb+srv://Myself:" + urllib.parse.quote("stackoverflow") + "#cluster0.4h226.mongodb.n...")
leveling = cluster["discord"]["leveling"]
class levelsys(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print('ready!')
#commands.Cog.listener()
async def on_message(self, message):
if message.channel.id in talk_channels:
stats = leveling.find_one({"id": message.author.id})
if not message.author.bot:
if stats is None:
newuser = {"id": message.auhor.id, "xp": 100}
leveling.insert_one(newuser)
else:
xp = stats["xp"] + 5
leveling.update_one({"id": message.author.id}, {"set":{"xp":xp}})
lvl = 0
while True:
if xp < ((50*(lvl**2))+(50*(lvl-1))):
break
lvl += 1
xp -= ((50*(lvl**2))+(50*(lvl-1)))
if xp == 0:
await message.channel.send(f"Well done {message.author.mention}: you advanced to **level: {lvl}**!")
for i in range(len(level)):
if lvl == levelnum[1]:
await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
embed = discord.Embed(
description= f"{message.author.mention} you have gotten role **{level[i]}**!!!"
)
embed.set_thumbnail(url=message.author.avatar_url)
await message.channel.send(embed=embed)
#commands.command()
async def rank(self, ctx):
if ctx.channel.id == bot_channel:
stats = leveling.find_one({"id": ctx.author.id})
if stats is None:
embed = discord.Embed(description="You need to write more messages to get the rank!")
await ctx.channel.send(embed=embed)
else:
xp = stats["xp"]
lvl = 0
rank = 0
while True:
if xp < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
xp -= ((50*((lvl-1)**2))+(50*(lvl-1)))
boxes = int((xp/(200*((1/2)*lvl)))*20)
rankings = leveling.find().sort("xp",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
embed.add_field(name="Name", value=ctx.author.mention, inline=True)
embed.add_field(name="Xp", value=f"{xp}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Level Bar", value=boxes*":blue_square:"+ (20-boxes)* ":white_large_square:", inline=False)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
#commands.command()
async def leaderboard(self, ctx):
if (ctx.channel.id == bot_channel):
rankings = leveling.find().sort("xp",-1)
i=1
embed = discord.Embed(title="Rankings:")
for x in rankings:
try:
temp = ctx.quild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline= False)
i+=1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
def setup(bot):
bot.add_cog(levelsys(bot))
error:
pymongo.errors.ConfigurationError: A DNS label is empty.
Please help me a little and tell me if there are other errors I need to fix. Thank you very much!

At a guess your issue is with the connection string; mongodb in "SRV" mode uses DNS to determine the replicaset / shard details.

Related

object has no attribute 'to_components'

I'm trying to make a blackjack command for my Discord Bot in python, I'm making small codes and little by little testing and improving, see below:
import discord
from discord.ext import commands
from discord import app_commands
import random, json, datetime
class bj(discord.ui.Button):
def __init__(self, game ,gamesum, player_cards):
super().__init__()
self.value = None
#discord.ui.button (label="Hit", style=discord.ButtonStyle.blurple)
async def confirm(self, button: discord.ui.Button, interaction: discord. Interaction):
self.value = True
self.stop()
value_1=["A", 1,2,3,4,5,6,7,8,9,10,"J","Q","K",]
nype_1=["♦️","♠️","♥️","♣️"]
card_value_3 = random.randint(0, len(value_1) - 1)
nype_card_3 = random.randint(0, len(nype_1) - 1)
card_3 = f"{card_value_3[card_value_3]} {card_value_3[nype_card_3]}"
await match.edit()
match.edit_field(name='Your hand', value=f"{player_cards} {card_value_3}{nype_card_3}")
if type(card_value_3)==str:
if value_card_3=="A":
value_letter_3=11
else:
value_letter_3=10
else:
value_letter_3=value_card_3
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def setup_hook(self) -> None:
self.add_view(DropdownView())
async def on_ready(self):
await aclient.change_presence(activity = discord.Streaming(name = "/news", url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"We entered as {self.user}!")
print(f"That has the ID {self.user.id}")
client = client()
tree = app_commands.CommandTree(aclient)
#tree.command(name='blackjack', description='Play a game of blackjack')
async def blackjack(interaction: discord.Interaction, amount:int):
await open_account(interaction.user)
money = await add_money(interaction.user)
if amount>money[0]:
await interaction.response.send_message(f"You don't have all this amount {interaction.user.mention}.")
else:
if quantity<0:
await interaction.response.send_message(f"You must enter a positive value")
else:
value_1=["A",2,3,4,5,6,7,8,9,10,'J','Q',"K"]
nype_1=["♦️","♠️","♥️","♣️"]
value_card_a = random.randint(0, len(value_1) - 1)
nype_card_a = random.randint(0, len(nype_1) - 1)
letter_a = f"{value_1[value_card_a]}{nype_1[nype_letter_a]}"
b_card_value = random.randint(0, len(1_value) - 1)
nype_card_b = random.randint(0, len(nype_1) - 1)
letter_b = f"{value_1[value_card_b]}{nype_1[nype_letter_a]}"
player_cards = f"{card_a} {card_b}"
if type(value_card_a)==str:
if value_card_a=="A":
value_letter_a=11
else:
value_letter_a=10
else:
value_card_a=value_card_a
if type(value_card_b)==str:
if value_card_b=="A":
value_letter_b=11
else:
value_letter_b=10
else:
value_card_b=value_card_b
sum_of_game=value_card_a+value_card_b
await add_money(interaction.user, -1*amount)
if sum_of_game==21:
result='Blackjack'
titulo_resultado=f'You won ~~K~~ {1.5*amount}'
else:
result=sum_of_game
titulo_resultado=f'You invested ~~K~~ {amount} in this blackjack'
departure=discord.Embed(
description=f'{result_title}',
colour=discord.Color.random()
)
match.add_field(name='Your hand', value=f"{player_cards}\n{result}")
if result=='Blackjack':
await add_money(interaction.user, 1.5*amount)
await interaction.response.send_message(embed=game, view=bj(game ,gamesum, player_cards))
async def open_account(user):
users = await bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]['wallet'] = 0
users[str(user.id)]['bank']= 0
with open("money.json", "w") as f:
json.dump(users, f)
return true
async def bank_data():
with open("money.json", "r") as f:
users = json.load(f)
return users
async def add_money(user, change=0, mode = "wallet"):
users = await bank_data()
users[str(user.id)][mode] +=change
with open("money.json", "w") as f:
json.dump(users, f)
money = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
return money
aclient.run(Token)
But in await interaction.response.send_message(embed=match, view=bj(match ,game_sum, player_cards)) is reporting the error
2023-02-06 19:14:31 ERROR discord.app_commands.tree Ignoring exception in command 'blackjack'
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 1155, in blackjack
await interaction.response.send_message(embed=partida, view=bj(partida ,soma_de_jogo, cartas_jogador))
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/interactions.py", line 754, in send_message
params = interaction_message_response_params(
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 577, in interaction_message_response_params
data['components'] = view.to_components()
AttributeError: 'bj' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'blackjack' raised an exception: AttributeError: 'bj' object has no attribute 'to_components'
I tried to interpret the error, as I recently started programming, it didn't help much, I asked in ChatGPT, and it also didn't help much (the error didn't even change), so the artificial intelligence itself suggested that I come and ask here, I hope it helps me help(Oh, and sorry for not leaving everything organized and well separated, they said there was a lot of code and little information).

How to stop a while loop in Discord.py

I have made a Discord Bot that pings members(spam Bot). It uses a while loop. It automatically stops in a few hours(IDK Why But probably because the host I use resets the connection after a few hours).
I wanna make a command so that the bot stops pinging members but still be online. Basically I wanna end the while loop I use. Can anyone help me?
import discord
from keep_alive import keep_alive
client = discord.Client()
roleid = os.environ["#PingersRoleID"]
CategoryID = os.environ["PingsCategoryID"]
PingChannels = [
"ping1",
"ping2",
"ping3",
"ping4",
"ping5",
"ping6",
"ping7",
"ping8",
"ping9",
"ping10",
]
PingBotToken = os.environ["PingBotToken"]
#client.event
async def on_ready():
print("{0.user} has joined the chat".format(client))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
# guild = client.get_guild(CategoryID)
print("{} sent {} in {}".format(username, user_message, channel))
if user_message.lower() == "!activatepings":
for _ in PingChannels:
if message.channel.name == str(_):
while True:
await message.channel.send("<#&{}>".format(roleid))
keep_alive()
client.run("...")
You can use a task that can be started and canceled at any time:
from discord.ext import tasks
#client.tasks(seconds=3600) #set to any amount
async def ping_task():
for channel in client.get_all_channels():
if channel.name in PingChannels:
await channel.send("<#&{}>".format(roleid))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
# guild = client.get_guild(CategoryID)
print("{} sent {} in {}".format(username, user_message, channel))
if user_message.lower() == "!activatepings":
for _ in PingChannels:
if message.channel.name == str(_):
ping_task.start() #The task starts here
#client.command()
async def someCommand(ctx):
ping_task.cancel() #The task ends with this command
You can find an example of how to use tasks here: https://github.com/Rapptz/discord.py/blob/v2.0.0/examples/background_task.py
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
# guild = client.get_guild(CategoryID)
print("{} sent {} in {}".format(username, user_message, channel))
if user_message.lower() == "!activatepings":
for _ in PingChannels:
if message.channel.name == str(_):
while True:
if message.content == "STOP": ## replace it with the command you want to stop the bot
break
else:
await message.channel.send("<#&{}>".format(roleid))

Discord.py commands wont work after i switched from Nextcord to Discord v2

I just switched to Discord.py v2 after switching using nextcord for 1 or 2 months.
Im having a issue where no commands work
like no commands at all
i changed everything from "nextcord" to "discord" and even changed the setups in the cogs to the new async versions
events work, but commands themselves dont
i tried everything i knew but still didnt fix it
i tried looking in the discord doc but still couldnt find a soloution
my current code:
import discord
from discord.ext import commands
from discord.ext.commands.core import has_permissions
import asyncio
import os
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='+', intents=intents)
##COGS
#bot.event
async def on_ready():
await asyncio.sleep(1)
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Game(name="in the Mountains"))
#bot.command()
#has_permissions(administrator = True)
async def load(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.load_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module loaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} loaded")
#bot.command()
#has_permissions(administrator = True)
async def unload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.unload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module unloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} unloaded")
#bot.command()
#has_permissions(administrator = True)
async def reload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.reload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module reloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} reloaded")
#load.error
async def alreadyloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [LOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Loaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#unload.error
async def alreadyunloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [UNLOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Unloaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
return
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#bot.command()
async def online(ctx):
print("1")
await ctx.channel.send("online")
print("hello")
async def main():
async with bot:
#await load_extensions()
await bot.start("bot auth code")
asyncio.run(main())
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to explicitly enable it in code and in the panel, at https://discord.com/developers/applications.
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='+', intents=intents)

EMBED SYSTEM [IDLE PYTHON]

So i have an embed system working in the below code:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
embedVar = discord.Embed(title="Title", description="desc", color=0x00ff00)
await message.channel.send(embed=embedVar)
My problem is yes when i do !emsay it dose put the embed in but is there a way that after i put !emsay i can change the title and description without going into python to type out a whole new embed?
This is what i currently have:(im fine with this)Discord screenshot of embed I would like to make it so after i use the command !emsay i can enter a title and description through discord.
Thanks : )
sorry if iv overcomplicated this
Try this:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
count = 0
def check(author):
def inner_check(message):
if message.author != author:
return False
return inner_check
while count < 2:
if (count == 0):
await message.channel.send("Write a title for embed")
title = await client.wait_for("message", check=check, timeout=30)
elif (count == 1):
await message.channel.send("Write a desc for embed")
desc = await client.wait_for("message", check=check, timeout=30)
count += 1
embedVar = discord.Embed(title = title.content, description = desc.content, color = 0x00ff00)
await message.channel.send(embed=embedVar)
If you don't write title and desc, you can get a TimeoutError and you can change timeout if you want.
How to use?

Discord.py snipe command is sniping messages from other channels

I recently made a snipe command for my discord bot but I have one problem. Snipe command snipes a message from other channels when I for example want to snipe a message in general. Here is my code:
#bot.event
async def on_message_delete(message):
if message.attachments:
bob = message.attachments[0]
bot.sniped_messages[message.guild.id] = (bob.proxy_url, message.content, message.author, message.channel.name, message.created_at)
else:
bot.sniped_messages[message.guild.id] = (message.content,message.author, message.channel.name, message.created_at)
#bot.command(aliases=['s'])
async def snipe(ctx):
try:
bob_proxy_url, contents,author, channel_name, time = bot.sniped_messages[ctx.guild.id]
except:
contents,author, channel_name, time = bot.sniped_messages[ctx.guild.id]
try:
embed = discord.Embed(description=contents , color=discord.Color.purple(), timestamp=time)
embed.set_image(url=bob_proxy_url)
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:
embed = discord.Embed(description=contents , color=discord.Color.purple(), 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)
snipe_message_author = {}
snipe_message_content = {}
#client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
#client.command(name = 'snipe')
async def snipe(ctx):
channel = ctx.channel
try:
em = discord.Embed(description = f"`{snipe_message_content[channel.id]}`\nMessage sent by {snipe_message_author[channel.id]}!", color = 0x00c230)
em.set_author(name = f"Last deleted message in #{channel.name}")
em.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096")
em.set_footer(text = f"Snipe requested by {ctx.message.author}")
await ctx.send(embed = em)
except:
embed = discord.Embed(colour = 0x00c230)
embed.set_author(name=f"There are no deleted messages in #{ctx.channel}!")
embed.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096")
embed.set_footer(text=f"Snipe requested by {ctx.message.author}")
await ctx.channel.send(embed=embed)
Thats what I use and it works properly.
Since I added [message.channel.id] to the variables it only checks for snipes in that channel. This is how it looks like in Discord

Resources