I want to send a random line from a .txt
from my discord bot, I am using nextcord
but if discord.py
works better I can use that to. Let me know if anyone can help.
I haven't tried much as I am fairly new to python but thought I would give it a try. I tried using random and .json
but it went horribly lol.
I'm not sure how nextcord works but there is a way you can get a random line from a .txt
file in any python file.
Firstly, make sure your .txt
file is in the same folder as your python file. Secondly we should import random as we will use random.choice
in this method. Then, you can create a function which chooses a random line from a text file which looks like this:
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
We can just call this function whenever we want to get a random line from a .txt
file.
Now that we have a way to get a random line from a .txt
file, we can implement this into discord.py
.This is how you would create this command in discord.py
import random
import discord
from discord.ext import commands
FILE_NAME = ""
YOUR_TOKEN = ""
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=">", intents=intents)
#The function that gets the random line
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
#Making the comand
@bot.command()
async def randomline(ctx):
await ctx.send(random_line(FILE_NAME))
bot.run(YOUR_TOKEN)
And remember to enable intents in the Developer Portal
If you would like to use nextcord
just try to use the function that I gave you to make this command. I hope this helps and if there were any problems just let me kow.