#commands.Cog.listener()
async def on_command(self, ctx):
with open(env["JSON_DIR"] + "servers.json", "r") as f:
s = json.load(f)
if not ctx.message.content == f"{ctx.prefix}verify":
if str(ctx.guild.id) in s:
command = self.bot.get_command(ctx.message.content.split(f"{ctx.prefix}")[1])
print(command)
command.update(enabled=False)
await ctx.send(embed=discord.Embed(title="No estais verificados", description="Para poder verificar el server poner `$verify`", color=0x00fbff))
else:
command = self.bot.get_command(ctx.message.content.split(f"{ctx.prefix}")[1])
command.update(enabled=True)
I want so that if the server is not verified the command that was executed to no be executed.
I have tried with command.update() but it doesn't really seem to work
Please help...
Related
I made a moderator bot but when i launch the code python writes "Process finished with exit code 0". Please check my if something wrong.
import discord
import config # Config is a another py file
client = discord.Client()
#client.event
async def on_message(message):
id = client.get_guild(config.ID)
badwords = ["testword", "testword2"]
unwarnusers = (config.unwarnusers)
for word in badwords:
if word in message.content.lower():
if str(message.author) not in unwarnusers:
warnFile = open("E:/vp2/warns.txt", "a")
warnFile.write(str(message.author.mention) + "\n")
warnFile.close()
warnFile = open("E:/vp2/warns.txt", "r")
warnedUsers = []
for line in warnFile:
warnedUsers.append(line.strip())
warnFile.close()
warns = 0
for user in warnedUsers:
if str(message.author.mention) == user:
warns += 1
if warns > 4:
mutedRole = discord.utils.get(message.guild.roles, name = "JB-MUTED")
await message.author.add_roles(mutedRole)
channel = client.get_channel(959128819137146900)
await channel.send(f"\nUser {message.author.mention} made something bad. \nHe writes:\n{message.content}\nThis happened in {message.channel}\n Warns: {warns}")
Add client.run('token') to the bottom of your code.
I'm trying to make a bot that would autoreact, check the amount of reactions on the messages in a channel, make a link to the message and send it on a moderation channel if it got 2 or more reactions, then log it's jump url in bot's directory. I cant find a way to fetch all the messages with jump_url and reactions attributes. im feeling super lost so i'll put the code here
async def on_message(message):
if message.channel.id == 828579458167996420:
channel = client.get_channel(828579458167996420)
if message.attachments or "http" in message.content:
await message.add_reaction("<:MashaUpset:828589397074116709>")
x = int
messages = await channel.history(limit=21).flatten()
f = open("message log.txt","r")
readfile = f.read()
f.close()
if str(messages.jump_url) not in readfile:
if messages.reactions[0].count >= 2:
x = messages.reactions[0].count - 1
link = messages.jump_url
channel = client.get_channel(892065611876823100)
await channel.send("this post was liked "+ str(x) + " times! "+ str(link))
f = open("message log.txt", "a")
f.write("\n" + str(messages.jump_url))
f.close()
im a beginner, so sorry for the mess i've made
Edit: can't fetch jump_url, so instead fetching for message.id
Ok I found it. thx to Dominik for help
Changes I've done
I've separated the script into 2 parts, an on_message and a #tasks.loop
Added a for x loop
Added an await channel.fetch_message(x.id) in the loop
Fetched for message.id rather than jump_url
Added if statement to check if the message has reactions
#client.event
async def on_message(message):
if message.channel.id == 828579458167996420:
if message.attachments or "http" in message.content:
await message.add_reaction("<:MashaUpset:828589397074116709>")
#tasks.loop(minutes=2)
async def check():
channel = client.get_channel(828579458167996420)
messages = await channel.history(limit=30).flatten()
await asyncio.sleep(3)
f = open("message log.txt","r")
readfile = f.read()
f.close()
for message in messages:
channel = client.get_channel(828579458167996420)
message = await channel.fetch_message(message.id)
if str(message.id) not in readfile:
if message.reactions:
if message.reactions[0].count >= 2:
x = message.reactions[0].count - 1
link = message.jump_url
channel = client.get_channel(892065611876823100)
await channel.send("this post was liked "+ str(x) + " times! "+ str(link))
f = open("message log.txt", "a")
f.write("\n" + str(message.id))
f.close()
#check.before_loop
async def before():
await client.wait_until_ready()
check.start()
I want to update an embed message that my bot has already written in a specific channel, how can I do that? If i try to use message.edit it givesthis error: discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
import discord
import json
from discord.ext import commands
def write_json(data,filename="handle.json"):
with open (filename, "w") as f:
json.dump(data,f,indent=4)
class Handle(commands.Cog):
def __init__(self, client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
print("Modulo_Handle: ON")
#commands.command()
async def Handlers(self,ctx):
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await ctx.channel.send(embed=embed)
file.close()
#commands.Cog.listener()
async def on_message(self, message):
if str(message.channel) == "solaris™-handle":
author = message.author
content = message.content
user = str(author)
with open ("handle.json") as file:
data = json.load(file)
temp = data['fields']
y={"name":user[:-5],"value":content}
temp.append(y)
write_json(data)
updated_embed = discord.Embed.from_dict(data)
await message.edit(embed=updated_embed)
file.close()
def setup(client):
client.add_cog(Handle(client))
msg_id = 875774528062640149
channel = self.client.get_channel(875764672639422555)
msg = await channel.fetch_message(msg_id)
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await msg.edit(embed=embed)
Fixed adding this code below write_json(data) and remove
updated_embed = discord.Embed.from_dict(data) await message.edit(embed=updated_embed)
def get_channel_id(client, message):
with open('./json/welcome.json', 'r') as f:
channel_id = json.load(f)
return channel_id[str(message.guild.id)]
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0x767429, description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f" {member.avatar_url} ")
embed.set_author(name=f" {member.name} ", icon_url=f" {member.avatar_url} ")
embed.set_footer(text=f"{ member.guild }", icon_url=f" {member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
channel = client.get_channel(id=get_channel_id)
await channel.send(embed=embed)
#client.command()
async def welcomechannel(ctx, channel_id):
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel_id
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to {channel_id}')
I'd like to have the get_channel_idfunction be the ID of the channel = client.get_channel(id=get_channel_id) but everytime I run it i get the error AttributeError: 'NoneType' object has no attribute 'send'. Can someone please help me
You can simplify the code quite a bit. As mentioned in my comment, you also need to open the JSON when a new user enters the server.
Your own function above is completely redundant and not needed.
I also once changed your welcomechannel command a bit because you don't get far with channel_id, you can use channel: discord.TextChannel instead and it comes out the same.
Here is the command for now:
#client.command()
async def welcomechannel(ctx, channel: discord.TextChannel): # We use discord.TextChannel
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel.id # Saving JUST the ID, you also had <#ID> in it
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to `{channel}`')
And now to check the channel. For that we open the JSON in the same way as we did with the command:
#client.event
async def on_member_join(member):
with open('./json/welcome.json', 'r') as f:
wchannel = json.load(f) # Define our channel
try:
if wchannel: # If a channel is set for the server
wchannelsend = member.guild.get_channel(wchannel[str(member.guild.id)]) # Get the channel from the JSON
embed = discord.Embed(color=0x767429,
description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f"{member.avatar_url} ")
embed.set_author(name=f"{member.name} ", icon_url=f"{member.avatar_url} ")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
await wchannelsend.send(embed=embed) # Send the embed to the channel
else:
return # If no channel was set, nothing will happen
except:
return
I have been trying to help a friend fix his discord bot, but I'm stumped on the solution.
from discord.ext import commands
import bs4
import requests
import time
import lxml
adminkey = "CheeseIsTheBest"
keys = open('keys.txt', 'w')
TOKEN = "token goes here"
client = commands.Bot(command_prefix = "!")
client.remove_command('help')
#client.event
async def on_ready():
print("Locked And Loaded Mr. DarkKnight")
#client.command(name='ping')
async def ping(ctx):
await ctx.send('pong')
#client.command()
async def addkey(ctx, key):
if str(ctx.author) == "ironkey#6969" or str(ctx.author) == "ZERO#2020":
with open('keys.txt', 'r+') as file :
file.write(str(key + "\n"))
file.close()
await ctx.send('key added')
else:
await ctx.send('your not authorized to preform this action ' + str(ctx.author))
#client.command()
async def redeemkey(ctx, key):
with open('keys.txt', 'r+') as file:
for line in file:
if str(key.strip()) == str(line.strip()):
with open('keys.txt', 'w') as file:
keyfile = keyfile.replace(str(key), key + " X")
file.write(keyfile)
file.close()
await ctx.send('key redeemed!')
else:
await ctx.send('This key has already been used')
#client.command()
async def unbind(ctx, *, member):
role = discord.utils.get(ctx.guild.roles, name='authenticated')
await client.remove_roles(member, role)
#client.command(aliases=['inv'])
async def invite(ctx):
await ctx.send('https://discordapp.com/api/oauth2/authorize?client_id=645664026160005129&permissions=8&scope=bot')
#client.command()
async def help(ctx):
embed = discord.Embed(color=discord.Color.dark_blue())
embed.set_author(name="Cheese Auth Help Menu", icon_url="")
embed.add_field(name=".ping", value="a simple fun command! usage : .ping")
embed.add_field(name=".invite", value="also used with the command inv, this command will get you an invite link so you can add this bot to your server! usage: .invite")
await ctx.send(embed=embed)
client.run(TOKEN)
Every time I try to redeem the key I added, I get this error:
Ignoring exception in command redeemkey:
Traceback (most recent call last):
File "C:\Users\seang\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79,
in wrapped ret = await coro(*args, **kwargs)
File "C:\Users\seang\Downloads\Bot_for_DarkKnight1-_Copy.py", line 41,
in redeemkey keyfile = keyfile.replace(str(key + X))
UnboundLocalError: local variable 'keyfile' referenced before assignment.
From your code i noticed that keyfile.replace is the problem. Variable keyfile is not assigned or declared (defined) yet.You are reading a file line by line in variable line so I think your code should be
keyfile = line.replace(str(key), key + " X")
The error comes from this line:
keyfile = keyfile.replace(str(key), key + " X")
You're trying to make a new value called 'keyfile', but it relies on information which comes from 'keyfile', which doesn't exist yet.