Is it possible to have multiple prefixes at once?
Example:
#discordbot help
;help (custom prefixes)
and in dms
\help
(I Got a working prefix changer and loader)
If there is, please show me a example or fix my broken code
the code:
import discord
import json
from discord import Embed
from discord.ext import commands
from discord.ext.commands import when_mentioned
def get_prefix(client, message):
guild = message.guild
if guild:
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(int(message.guild.id))]
elif not guild:
return ','
else:
return when_mentioned(client, message)
client = commands.client(command_prefix=get_prefix)
#client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(int(guild.id))] = '//'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(int(guild.id)))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#client.command()
async def prefix(ctx, *, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(int(ctx.guild.id))] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
#client.command()
async def ping(ctx):
await ctx.send('pong')
#client.event
async def on_ready():
print('ready')
client.run(token)
if not, please show me an example, Thanks
You can just make it like
prefixes = ";", "/"
bot = commands.Bot(command_prefix=prefixes)
Related
Oh and another problem it has is that it doesnt print the user_message in console as it should in line 12
client = discord.Client(command_prefix='',intents=discord.Intents.default())
#client.event
async def on_ready():
print('logged in as {0.user}'.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)
print(f'{username}: {user_message} ({channel})')
if user_message == 'Hello':
await message.channel.send('Howdy!')
Any help would be appreciated!
Your indentation is all messed up here; starting with your second client.event, your code is indented way too far; here's how the code should look:
client = discord.Client(command_prefix='',intents=discord.Intents.default())
#client.event
async def on_ready():
print('logged in as {0.user}'.format(client))
# Indentation fixed here
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if user_message == 'Hello':
await message.channel.send('Howdy!')
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))
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)
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.
I'm working in discord.py rewrite and want to make a command called ~warn <user> <reason> that warns the user and ~warns <user> that shows the amount of warns that the user has. I have looked for a tutorial on this but almost all of them were in discord.js, and the ones that were in discord.py were all in async. Can someone help me code this?
You can use the JSON Module for it, I'll make the command,
async def update_data(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['warns'] = 0
async def add_warns(users, user, warns):
users[f'{user.id}']['warns'] += 1
#client.command()
async def remove_warn(ctx, user: discord.Member, amount: int=None):
with open('warns.json', 'r') as f:
users = json.load(f)
amount = amount or 1
await update_data(users, user)
await add_warns(users, user, -amount)
if users[f'{user.id}']['warns'] <= 0:
with open('warns.json', 'w') as f:
del users[f'{user.id}']['warns']
del users[f'{user.id}']
f.write(json.dumps(users, indent=4))
return
else:
with open('warns.json', 'w') as f:
json.dump(users, f, sort_keys=True, ensure_ascii=False, indent=4)
await ctx.send(f'Removed {amount} warn for {user}')
return
#client.command()
async def warns(ctx, user: discord.Member=None):
user = user or ctx.author
try:
with open('warns.json', 'r') as f:
users = json.load(f)
warns = users[f'{user.id}']['warns']
await ctx.send(f'{user} has {warns} warnings')
except:
await ctx.send(f'{user} dont have any warnings.')