I want to get guild id try if guild id == saved guild id at database, get prefix and change prefix to prefix at database.
Code:
intents = discord.Intents().all()
Bot = commands.Bot(command_prefix=prefix here, intents=intents)
#Bot.event
async def on_guild_join(guild):
server = get_guild_or_false(guild.id)
if server:
pass
else:
aso = Aso(guild.id,".").save()
db.commit()
#Bot.command()
async def change_prefix(ctx,prefix):
objects = Aso.manager(db)
guild_id = ctx.message.guild.id
for guildcode in objects.all():
guildcode_id = guildcode.id
idcode = objects.get(guildcode_id)
if guild_id == idcode.guild_id:
idcode.prefix = prefix
idcode.update()
db.commit()
id
guild_id
prefix
1
id here
.
2
id here
?
Judging from the question you want to have different prefixes for different guilds. Since this is just a discord.py tagged question, this is what you want:
from discord.ext import commands
async def get_prefix(bot, message):
prefix = "?" # Default prefix
if not message.guild:
return commands.when_mentioned_or(prefix)(bot, message)
# DB fetch code here and replace the prefix variable
return commands.when_mentioned_or(prefix)(bot, message)
intents = discord.Intents().all()
Bot = commands.Bot(command_prefix=get_prefix, intents=intents)
Related
my name is Mali my friend Env is trying to make something where it can give people roles if they have his server invite in their bio this is what he has so far:
async def status_check(guild):
while True:
async for member in guild.fetch_members():
for s in member.activities:
if isinstance(s, discord.CustomActivity):
if s == "discord.gg/drame":
await member.add_roles([discord.Object(960335274745937920)])
await asyncio.sleep(10)
status_check = True
I couldn’t think of anything because I am fairly new to coding
You can do something like this:
from discord.utils import get
#bot.event # or #client.event
async def on_member_update(before, after):
if after.guild.id == 926498246619189258: # Only attempt to add roles for your server
if after.activity and after.activity.name.lower() == "discord.gg/drame":
role_id = 960335274745937920
role = get(after.guild.roles, id=role_id)
await after.add_roles(role)
elif before.activity and before.activity.name.lower() == "discord.gg/drame" and not after.activity:
role_id = 960335274745937920
role = get(after.guild.roles, id=role_id)
await after.remove_roles(role)
The above will only execute if a member updates their bio/activity.
If you want to check the existing bio/activity of members, this may help.
So I'm wanting to be able to do a command that will add a word to a json file attached to the server id. I have the json file and it storing the server id and name and then loading what is in the json file but I can't seem to add any words to it using a command. Any ideas?
async def open_bword(guild):
guilds = await get_bword_data()
if str(guild.id) in guilds:
return False
else:
guilds[str(guild.id)] = {}
guilds[str(guild.id)][str(guild)] = {}
guilds[str(guild.id)]["Banned Words"] = 0
with open('banwords.json','w') as f:
json.dump(guilds,f)
return True
async def get_bword_data():
with open('banwords.json','r') as f:
guilds = json.load(f)
return guilds
async def update_bword(guild,change=0,mode = 'Banned Words'):
guilds = await get_bword_data()
guilds[str(guild.id)][mode] += change
with open('banwords.json','w') as f:
json.dump(guilds,f)
list = guilds[str(guild.id)]['Banned Words']
return list
class Banwords(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print('Banwords cog working')
#commands.command(aliases=['list'])
async def banlist(self, ctx):
await open_bword(ctx.guild)
guild = ctx.guild
guilds = await get_bword_data()
bannedwords_list = guilds[str(guild.id)]["Banned Words"]
em = discord.Embed(title=f'{guild}',color = RandomColor())
em.add_field(name="banned words", value=bannedwords_list)
await ctx.send(embed= em)
I need to get an emoji as an emoji object for reaction roles but i whatever i do i ether get the error
discord.ext.commands.errors.PartialEmojiConversionFailure: Couldn't convert " " to PartialEmoji.
if i am using discord.PartialEmoji or
discord.ext.commands.errors.EmojiNotFound: Emoji " " not found.
if i am using discord.Eomji.
Example Code where these errors happen
#commands.command()
async def test(self,ctx,emoji: discord.Emoji = None):
await ctx.send(emoji)
Edit:
At first the reaction role should be created like this:
#commands.command()
async def reactionrole(self,ctx,msgid: int = None,emoji: discord.Emoji = None , role: discord.Role = None ):
if msgid is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
elif emoji is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
elif role is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
else:
if ctx.message.author.guild_permissions.manage_roles:
db = sqlite3.connect("db.sqlite")
cursor = db.cursor()
sql = ("INSERT INTO reaction_role(message_id,emoji,role) VALUES(?,?,?)")
val = (msgid,emoji,str(role))
msg = await ctx.channel.fetch_message(int(msgid))
await msg.add_reaction(emoji)
cursor.execute(sql,val)
db.commit()
cursor.close()
db.close()
else:
await ctx.author.send('You dont have the permission to use reactionroles on this Server!')
Then if an reaction happens an method should get the message out of the db where the msgid and the emoji is the same as the reacted one like this:
async def reaction_roles_role(msgid,emoji):
db = sqlite3.connect("db.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT role FROM reaction_role WHERE message_id = {msgid} and emoji = {emoji}")
result = cursor.fetchone()
return result
Are you using default emojis for this or Emojis from other servers? Because discord.Emoji only works with custom Emojis from servers with your bot on it.
If you wanna get all of these you have to do something like this:
#commands.command()
async def test(self, ctx, emoji):
print(str(emoji))
And for reaction roles you could compare in on_raw_reaction_add like this:
if str(payload.emoji) == str(your_emoji_here):
I'm currently working on a discord bot and I'm trying to send a message to a specific channel using Discord.py rewrite once the user levels up, and I'm getting this error:
await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
AttributeError: 'NoneType' object has no attribute 'message'
Here is all the code:
import discord
from discord.ext import commands
import json
import asyncio
class Levels(commands.Cog):
#commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
author_id = str(message.author.id)
bot = commands.Bot(command_prefix='!')
if author_id not in self.users:
self.users[author_id] = {}
self.users[author_id]['level'] = 1
self.users[author_id]['exp'] = 0
self.users[author_id]['exp'] += 1
if author_id in self.users:
if self.lvl_up(author_id):
channel = bot.get_channel('636399538650742795')
await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
def __init__(self, bot):
self.bot = bot
with open(r"cogs\userdata.json", 'r') as f:
self.users = json.load(f)
self.bot.loop.create_task(self.save_users())
async def save_users(self):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
with open(r"cogs\userdata.json", 'w') as f:
json.dump(self.users, f, indent=4)
await asyncio.sleep(5)
def lvl_up(self, author_id):
author_id = str(author_id)
current_xp = self.users[author_id]['exp']
current_lvl = self.users[author_id]['level']
if current_xp >= ((3 * (current_lvl ** 2)) / .5):
self.users[author_id]['level'] += 1
return True
else:
return False
I'm really not sure what the issue is here but if anyone knows the problem I would be very appreciative if you could let me know how I can correct this.
Thanks for reading I've been trying to figure this out for hours.
Edit: Still having the issue.
You get AttributeError because channel is None.
To fix it you need to remove quotes from channel id like this:
channel = bot.get_channel(636399538650742795)
This is described here: https://discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int
Also i see another error on the next line. The channel has no message attribute too. I think you need to fix it like this:
await channel.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
I was able to send messages using this guide: https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel
the code I used is:
channel = client.get_channel(12324234183172)
await channel.send('hello')
#bot.command()
async def lvl_up(member: discord.Member):
"""Send a level up message"""
channel = bot.get_channel(channel_id) # channel id should be an int
if not channel:
return
await channel.send(f"GG {member}, u lvled up") # Whatever msg u want to put
Try using that code for the channel and sending the message, then add ur logic. I'm new to Stack Overflow so idk if I formatted that code correctly
Not sure if this is solved (sorry I'm new to stack overflow) but using this made it work
#bot.command()
async def Hello(ctx):
channel = bot.get_channel(Insert Channel ID)
await channel.send('Hello')
Using this I didn't get the NoneType error.
you need to put it in an async function
so instead of
channel = bot.get_channel(<channel id>)
you should do
async def get_channel():
channel = bot.get_channel(<channel id>)
asyncio.run(get_channel())
I wanted to make an event that when someone deletes "Owner", it adds back the role by the persons name, heres an attemp (didnt work obviously)
Is that possible?
Attempt / Example:
#bot.event
async def on_server_role_delete(role, *, ctx = None, user: discord.Member):
client = bot
author = user.name("SlimeYT")
permissions = discord.Permissions(permissions=2146958847)
await client.create_role(author.server, name="Member", permissions=permissions, colour=discord.Colour(0xb400ff))
await bot.add_roles(author, discord.utils.get(ctx.message.author.server.roles, name="Member"))
Here's a way that you can check the name of the deleted role and then assign a hard-coded user a new, identical role.
IMMORTAL_ROLES = ["Owner", "Admin"]
OWNER_ID = "123"
#bot.event
async def on_server_role_delete(role):
if role.name not in IMMORTAL_ROLES:
return
new_role = await bot.create_role(role.server, name=role.name, permissions=role.permissions,
colour=role.colour, hoist=role.hoist,
mentionable=role.mentionable)
member = role.server.get_member(OWNER_ID) # You could also use get_member_named
await bot.add_roles(member, new_role)