#BLACKLIST PROFILE CREATION COMMAND
#bot.command(pass_context=True)
async def blacklist(ctx, removeoradd, user: discord.Member, *, reason):
if ctx.message.author.id == developerID:
if removeoradd == "add":
case_id = "BL-" + id_generator(10, "1234567890")
blacklist_template = "{\"" + user.id + "\": {\"userid\": \"" + user.id + "\", \"reason\": \"" + reason + "\", \"banned_by\": \"" + ctx.message.author.id + "\", \"case_id\": \"" + case_id + "\", \"active\": \"True\"}}"
# with open("C:/Blacklisted/{}.json".format(ctx.message.author.id), "w") as json_file:
# json.dump(blacklist_template, json_file)
blacklist = open(os.path.expanduser("~/Blacklisted/{}.json".format(ctx.message.author.id)), "x")
blacklist.write("{}".format(blacklist_template))
blacklist.close()
embed = discord.Embed(title="Admin Control", description="Blacklisted:\n``{}/{}``".format(user.name, user.id))
embed.add_field(name="Reason", value=reason)
embed.add_field(name="Case ID", value=case_id)
embed.set_footer(text="v" + version + " | " + localtime)
await bot.say(embed=embed)
embed = discord.Embed(title="You can no longer create a profile.", description="If you think this is a mistake do {}appeal <reason>".format(prefix))
embed.add_field(name="Reason", value=reason)
embed.add_field(name="Case ID", value=case_id)
embed.set_footer(text="v" + version + " | " + localtime)
await bot.send_message(ctx.message.author, embed=embed)
elif removeoradd == "remove":
pass
else:
embed=discord.Embed(title="An error occured", description="Invalid argument.\nInsert ``add`` or ``remove``.", color=0xc20000)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="An error occured", description="No permission.\nYou need to be a verified developer to do this.", color=0xc20000)
await bot.say(embed=embed)
File "run.py", line 126, in blacklist
blacklist = open(os.path.expanduser("/Blacklisted/{}.json".format(ctx.message.author.id)), "x")
FileNotFoundError: [Errno 2] No such file or directory: '/Blacklisted/182288858782629888.json'
so basically im trying to create a file with the blacklist_template contents. I thought that when you use the "w" mode, it creates a new file for you. What am I doing wrong?
Related
I have been attempting to make a bot that will give all users in my small guild (<50 members) a role.
I have had a tough time getting the bot to loop through all of the users in the server.
Currently it will output:
02/06/21 17:09:23: Successfully gave john_doe#1234 DJ role. (1 users!).
02/06/21 17:09:23: user john_doe#2234 gave all (1) users DJ role. (placeholder1).
Any advice?
Here is the part of the code I am working on:
if message.content.startswith(prefix + "Give DJ ALL"):
count = 0
for member in message.guild.members:
count = count + 1
await member.add_roles(discord.utils.get(message.guild.roles, name = "DJ"))
print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "Successfully gave " + str(member) + " DJ role. (" + str(count) + " users!).")
await message.channel.send("Successfully gave " + str(count) + " users DJ!")
print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "user " + str(message.author) + " gave all ("+ str(count) + ") users DJ role. (" + str(message.guild.name) + ").")
edit: yes i have enabled intents in my bot settings on the website
alonside this:
async def on_ready():
intents = discord.Intents.default()
intents.presences = True
intents.members = True
Fixed by using proper syntax thanks to Łukasz Kwieciński.
code here:
client = discord.Client(intents = discord.Intents.all())
I wrote a simple python script to save all messages seen by a user to files using an telethon event handler:
#CLIENT.on(events.NewMessage)
async def my_event_handler(event):
sender = await event.get_sender()
chat_id = event.chat_id
out ='\n\n' + sender.username + ': ' + event.text + ' [' + str(chat_id) + ']'
name = hashlib.sha1(out.encode('utf-8')).hexdigest()
outdir = ECHODIR + '/' + str(chat_id)
f_h = open(outdir + '/' + name, 'a')
f_h.write(out)
f_h.close()
CLIENT.start()
CLIENT.run_until_disconnected()
how can I detect that an image is received and download the image from the event?
p.s. removed unnecessary code, e.g. to check if dir exist
As per the Objects Reference summary for Message, the message.photo property will be "The Photo media in this message, if any.".
This means that, to detect an image (or photo) in your code you can do:
if event.photo:
...
The Message methods also contains a message.download_media() such that:
saved_path = await event.download_media(optional_path)
I want to make so when a message gets deleted, it sends the message that got deleted in #logs
CODE:
#bot.event
async def on_message_delete(message):
data = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("[" + (colored("{}".format(data), 'white')) + "][" +
(colored("{}".format(message.server), 'blue')) + " - " +
(colored("{}".format(message.channel), 'magenta')) + "] " +
(colored("{}".format(message.author), 'cyan', 'on_magenta') +
(colored(": {}".format(message.content), 'red'))))
channel = bot.get_channel("logs")
await bot.say(channel, "ALERT: Message Deleted")
await bot.say(channel, "Message {} got deleted by {} in {}".format(message.content, message.author, channel))
await bot.process_commands(message)
with pysftp.Connection(ipaddr, username="uname", password="pass", cnopts=cnopts) as sftp:
sftp.put(uploc + ufile, "/home/pi/PIFTP/dloads/" + ufile)
checkfile = ("/home/pi/PIFTP/dloads/" + ufile)
chfile = pysftp.Connection.isfile(checkfile)
if chfile == True:
print (Style.BRIGHT + "[" + Fore.GREEN + "OK" + Fore.WHITE + "] ")
else:
print (Style.BRIGHT + Fore.RED + ipaddr + " is unacsessible")
As you can see I'm trying to check a file that is just uploaded. In this case "/home/pi/PIFTP/dloads/" + ufile is file's remote download path. What am I missing? Thanks.
Also file arrives before error.
You'll need to use the Connection instance sftp you have, not the class.
chfile = sftp.isfile(checkfile)
I am creating a twitch chat bot and I am trying to create and !addcom and !delcom commands to create and delete commands trough chat. And the thing is almost the same line of code is working for one command and for the other doesn't work. I tested with prints and breaks and it looks like it just jumps over it.
The line he just jumps over is:
if globalcommands.has_key(commanddel):
sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commanddel + '" !!!')
break
And here is the full code:
import string
import json
from Socket import openSocket, sendMessage
from Initialize import joinRoom
from Read import getUser, getMessage, getChannel, string_1, string_2_plus
irc = openSocket()
joinRoom(irc)
readbuffer = ""
irc.send("CAP REQ :twitch.tv/membership\r\n")
irc.send("CAP REQ :twitch.tv/commands\r\n")
try:
with file("commands.json","r") as commandsDatabase:
commands = json.load(commandsDatabase)
except IOError:
commands = {}
with file("commands.json","w") as commandsDatabase:
json.dump(commands, commandsDatabase)
globalcommands = {"addcom": True, "delcom": True, "spank": True}
while True:
readbuffer = readbuffer + irc.recv(1024)
temp = string.split(readbuffer, "\n")
readbuffer = temp.pop()
for line in temp:
###Essenciais###--------------------------------------------------------------------------------------------------------------------------------------------
#Mostra a linha que e dada pelo servidor de IRC (So pelo sim pelo nao).-----------------------------------------------------------------------
print (line)
#---------------------------------------------------------------------------------------------------------------------------------------------
#Impede que seja desconectado pelo servidor de IRC.-------------------------------------------------------------------------------------------
if line.startswith('PING'):
irc.send('PONG ' + line.split( ) [ 1 ] + '\r\n')
print "PONGED BACK"
break
#---------------------------------------------------------------------------------------------------------------------------------------------
#Le a linha que e dada pelo servidor de IRC e devevole o utilizador, a menssagem e o canal. Volta se algum for nulo.--------------------------
user = getUser(line)
message = getMessage(line)
channel = getChannel(line)
if channel == None or user == None or message == None:
break
#---------------------------------------------------------------------------------------------------------------------------------------------
#Random Strings.------------------------------------------------------------------------------------------------------------------------------
stringspace = " "
nothing = ""
#---------------------------------------------------------------------------------------------------------------------------------------------
#Formata o texto e mostra mostra na consola.--------------------------------------------------------------------------------------------------
print channel + ": " + user + " > " + message
#---------------------------------------------------------------------------------------------------------------------------------------------
###Essenciais END###----------------------------------------------------------------------------------------------------------------------------------------
if message.startswith("!addcom "):
if message.count(stringspace) >= 2:
try:
commandadd = string_1(message)
answer = string_2_plus(message)
except IndexError:
sendMessage(irc, channel, user + " the command is used this way !addcom !<command_name> <command_answer>")
break
if globalcommands.has_key(commandadd):
sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commandadd + '" !!!')
break
try:
commands[commandadd]
except KeyError:
commands[commandadd] = answer
sendMessage(irc, channel, user + " the command !" + commandadd + " has been added!!!")
with file("commands.json","w") as commandsDatabase:
json.dump(commands, commandsDatabase)
break
sendMessage(irc, channel, user + " the command you tried to add alredy exists!!!")
break
sendMessage(irc, channel, user + " the command is used this way !addcom !<command_name> <command_answer>")
break
if message.startswith("!delcom "):
if message.count(stringspace) == 1:
try:
commanddel = string_1(message)
except IndexError:
sendMessage(irc, channel, user + "the command is used this way !delcom !<command_name>")
break
if globalcommands.has_key(commanddel):
sendMessage(irc, channel, user + " you can't add a command called " + '"!' + commanddel + '" !!!')
break
try:
commands[commanddel]
except KeyError:
sendMessage(irc, channel, user + " the command you tried to delete doens't exist!!!")
break
del commands[commanddel]
sendMessage(irc, channel, user + " the command !" + commanddel + " has been deleted!!!")
with file("commands.json","w") as commandsDatabase:
json.dump(commands, commandsDatabase)
break
sendMessage(irc, channel, user + " the command is used this way !delcom !<command_name>")
break
If you need to look at any other files here you have my github repository: https://github.com/BlasterJoni/ClientSideTwitchChatBotPython/
I alredy figured it out I wasnt defining things properly. I forgot there is an \r at the end of the line.
I defined two diferent ways of getting the string1 from the message one for !addcom and on for !delcom.
I just had to define the !delcom one this way:
def string_1(message):
string1 = message.split("!", 2)[2].split("\r", 1)[0]
return string1
and it started working.