Discord.py saving unknown channel messages into txt file - python

async def on_message(self, message):
if message.author == self.user:
return
if message.content.lower() == 'hi':
await message.channel.send('hello')
if message.content.lower() == '':
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("" + f.name) # Write inside file
f.close()
If someone sends a message in a discord channel, and the message does not contain the word, "hi", I want it to save the unknown message into an existing text file. Without using client commands or code.

I know you asked not to receive code, but I am going to have to.
This portion:
if message.content.lower() == '':
f = open("Path/To/Your/File.txt", "w")
f.write(""+f.name)
f.close()
Seems to check if a user sends a blank message (should be impossible, since you have to send some thing in discord), and opens Path/To/Your/File.txt in write mode, and writes in the name of it (File.txt). Also, lower() makes the text lowercase, and that is not needed since you cant have an uppercase nothing.
Also, the Path/To whatever means you would have to create three folders, path, to, and your, and then put a File.txt in your. You should put a file.txt in your current folder, and change that /Path/To to just file.txt.
It does not check if the bot does not have a response.
You should completely remove that section.
Step 1:
    Create a file called like log.txt.
Step two:
    Replace that section of code with:
#checks if the bot has a response
knownmessages = ["hi"] #you can add more
if message.content not in knownmessages:
f = open("log.txt", "a") #or what you called it. also a for append, it would overwrite otherwise.
f.write(message.content + "\n") #\n means new line
f.close()
You seem to be a beginner, so don't worry. I remember when I was a beginner.

According to your comment, I think you want to log the messages to a text file only if the bot does not have a response for it.
So here's how you could structure your on_message function:
Define the function as async def on_message(self, message)
After this you can check if you sent the message:
if message.author == self.user:
return
Then you can add specific responses for specific strings:
if message.content.lower() == "hi":
await message.channel.send("hello")
return
Now's where the important part comes in:
First you create a context by using self.get_context(message)
After this you have to check if the context can be used to invoke a command. If yes, then the context is valid, and you can invoke the command.
If the context is invalid, then you can log the contents to a file.
if context.valid():
await self.invoke(context)
return
If none of these if clauses trigger, then that means the bot does not have a reponse for the message. So you can log it to the file.
with open("path/to/file.txt", 'a') as f: # a for append
f.write(message.content + '\n')
So your final on_message method will be:
async def on_message(self, message):
# Check if the bot sent the message.
if message.author == self.user:
return
# Reply to some predetermined strings of text
if message.content.lower() == "hi":
await message.channel.send("hello")
return
# Create a context from the message
context = await self.create_context(message)
# If the context is valid, then invoke the command
if context.valid:
await self.invoke(context)
return
# Append to file if the bot does not have a respone to the message
with open("path/to/file.txt", 'a') as f:
f.write(message.content + '\n')

Related

Check if user send a .mp4 file with specified name to bot's Dm

I need to check if user sends a .mp4 file with specified name (for example: pizza), and if that's true, bot send a message. Is there's a way i can do that?
There's a better way to do this that isn't addressed in the dupe. The file object contains an attribute filename. You can then iterate over all the attachments and check for the file:
for file in <your message object goes here>.attachments:
if file.url == 'pizza.mp4':
# do stuff
if ctx.message.attachments: #checks if there are any attachments
for attachment in ctx.message.attachments: #checks all attachments if there are multiple
if str(attachment) == "pizza.mp4":
print("found attachment!")
Try this in your on_message event:
#bot.event
async def on_message(message):
if message.guild is None and message.author != bot.user: # dm message
try:
file = message.attachments[0] # try getting the file
if "pizza" in str(file.filename): # check if name is in the filename
await ctx.send("message") # send message
else:
await ctx.send(f"pizza not found in {str(file.filename)}")
except: # user did not send a file/attachment
await ctx.send("no file sent")

discord.py add different str object to different users

So I'm trying to make a command that adds the name of a song to an user. I just don't understand how I should do that. I tried looking on the dictionary documentations but I couldn't find anywhere how I could append a variable to a certain person. This is my current code altough I think it's completely wrong:
#commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
quotes.append(quote)
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
You can use this with a dictionary and track them by ID. Be careful with this, as JSON does not allow you to use integers as keys to anything. Only strings are allowed.
#commands.command()
async def quote(self, ctx):
await ctx.send("add your quote")
msg = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
quote = msg.content
with open('quotes.json', 'r') as f:
quotes = json.load(f)
strid = str(msg.author.id) # this is necessary for json
if strid not in quotes.keys():
quotes[strid] = []
quotes[strid].append('My quote, or put whatever you need to add in here')
with open('quotes.json', 'w') as f:
json.dump(quotes, f)
await ctx.send("quote added!")
As a sidenote, it's a bad idea to open the file and close it multiple times. Instead, you can try a construct like this, and then you will be spared from opening the file so much:
client = commands.Bot(...)
with open('quotes.json', 'r'):
client.quotes_data = json.load(f)
#tasks.loop(minutes=3.0) # adjust this at your liking, or execute it manually
async def save_all():
with open('quotes.json', 'w'):
json.dump(client.quotes_data, f)
save_all.start()
If you're trying to make it so users can request multiple songs in a queue type fashion, I'd create a dictionary, make the key the user (the message's author)'s ID (ctx.author.id) and set the value to an empty list, then append to that list the user's requested song's name.
On the other hand, if you prefer one song per user, just set the value to the song for the user's ID's key.
This would typically use just casual key assignments for dictionaries.
An example of how this would work (assume this is inside your command):
songs = {};
# This code if you'd like multiple songs per user.
songs[ctx.author.id] = [];
songs[ctx.author.id].append("SONG VALUE HERE");
# This code if you'd like one.
songs[ctx.author.id] = "SONG VALUE HERE";

Reload discord bot after prefix change (Discord.py)

The problem is I want to dynamically change my prefix with a command. The prefix gets updated in the json file but the only problem is that the bot needs to reload to accept the new prefix. So I need a way to make the bot read the new prefix instantly after updating it in the config.json.
JSON FILE:
"command_prefix": "."
UPDATE PREFIX CMD: (The command is in my core cog)
# PREFIX CHANGE COMMAND
#commands.group(name="prefix", invoke_without_command=True)
#commands.has_permissions(administrator=True)
async def prefix(self, ctx):
current_prefix = get_config_file("command_prefix")
await ctx.channel.send(f'Current prefix is: **{current_prefix}** \n If you want to change the prefix use subcommand: _set_')
#prefix.command(name="set")
#commands.has_permissions(administrator=True)
async def set(self, ctx, mode):
mode != None
with open('config.json', 'r') as f:
config = json.load(f)
config["command_prefix"] = mode
with open('config.json', 'w') as f:
json.dump(config, f, indent=4)
f.close()
await ctx.channel.send(f'Prefix has been changed to `{mode}`')
When you first initialize a bot, it creates a prefix and uses that prefix only until you recreate the bot. If you want the bot to have a different prefix or update it, you need a callback on the command_prefix argument.
First create the get_prefix function.
async def get_prefix(bot, message): # you can also do it by guild with message argument
return get_config_file("prefix_command")
then in the Bot instance
bot = commands.Bot(command_prefix=get_prefix)
Note: These both will be in the main file where you create the bot. It will change immediately every time you update the prefix.

discord.py retrieving data from json file not responding

Sorry for the unclear question title. I don't know any other way to put it.
I made a command that says p!channel [channel_id] which basically makes a channel where my bot will respond with "e". I want the command to store the channel_id and guild_id into a json file called channel.json, and when a user sends a message, it will check if the message is in the channel_id channel, and if it is in the channel, will send "e". However, it's not responding and no error codes are showing up. Can someone help? Code is below:
def get_channel(client,message):
with open("channel.json", "r") as f:
e = json.load(f)
return e[str(message.guild.id)]
#client.command()
#commands.has_permissions()
async def channel(ctx, *, channelid):
with open("channel.json", "r") as f:
e = json.load(f)
e[str(ctx.guild.id)] = channelid
with open("channel.json", "w") as f:
json.dump(e,f)
await ctx.send(f"Successfully setup <#{channelid}>")
#client.event
async def on_message(message):
if message.channel.id == get_channel:
await message.channel.send('e')
There are several immediate problems that are keeping this from functioning.
You're only referencing get_channel, not calling it. The channel's ID isn't equal to the function itself, so the message is never sent. You want get_channel(client, message).
Your on_message event ensures that your command never gets called.
You attempt to use ctx.send() instead of ctx.channel.send().
Channel IDs are integers, but command arguments are always read in as strings. Without converting the argument to an integer, comparing it against a channel's ID will always return False.
In addition, there are several things you could improve:
The get_channel function doesn't ever use client, so you could alter your function definition to simply get_channel(message).
Furthermore, channel IDs are globally unique, so you don't need to save the guild ID in order to unambiguously identify a channel.
It would be more efficient not to read the whole file every time you need to check for an ID.
The has_permissions check doesn't check anything if you supply it no arguments, so in your code it does nothing.
You probably don't want your bot to respond to its own messages.
Here's an improved version that reads a saved file on startup, if one exists. It then keeps the IDs as a set in memory, and only opens the file when it needs to add a new ID.
from discord.ext import commands
import json
client = commands.Bot(command_prefix='p!')
try:
with open('channels.json') as f:
client.ids = set(json.load(f))
print("Loaded channels file")
except FileNotFoundError:
client.ids = set()
print("No channels file found")
#client.command()
async def channel(ctx, channel_id):
try:
channel_id = int(channel_id)
except ValueError:
await ctx.channel.send("Channel must be all digits")
return
if channel_id in client.ids:
await ctx.channel.send(f"Channel <#{channel_id}> is already set up.")
return
client.ids.add(channel_id)
with open('channels.json', 'w') as f:
json.dump(list(client.ids), f)
await ctx.channel.send(f"Successfully set up <#{channel_id}>")
#client.event
async def on_message(message):
if message.channel.id in client.ids and message.author != client.user:
await message.channel.send('e')
# Pass processing on to the bot's command(s)
await client.process_commands(message)
client.run(TOKEN)

How to make the command can be disabled on certain servers discord py

I want to make a list with a list of id discord servers that want to disable some of the functions of my bot.
For example: the on_member_join method will not send a message when a person enters the server, and on the other where this function is enabled, it will send that the person has connected to the server. But I don't know how to properly store the id and use it. At the moment there is this:
async def serverid(ctx):
sid = ctx.message.guild.id
await ctx.send(sid)
sid = 705735563696799723 (id server dependent)
that's roughly what I want to get in the end
async def test(ctx):
f = open('/app/commands/servers.txt', 'r')
servers_sid = f.readlines()
now_sid = ctx.message.guild.id
if now_sid == servers_sid: #i know servers_sid = ['id'] or something similar this is what i have a problem with
await ctx.send('Command disabled')
else:
#command execution
i know servers_sid = ['id'] or something similar this is what i have a problem with
You should use splitlines so that you will not carry the \n. I made the check to be not in if it is not in the file then it will just end
async def test(ctx):
with open('/app/commands/servers.txt', 'r') as f:
servers_sid = f.read().splitlines()
now_sid = str(ctx.message.guild.id)
if now_sid not in servers_sid:
await ctx.send('Command disabled')
return
await ctx.send('This is working')
#command execution
I am assuming you txt file is like this.
123
456
789

Categories

Resources