'How do I get a random line from a file and send it as a discord bot?
I'm new to python and I'm trying to get a discord bot to send a random line from a text file. So far i have this code, but it wont send when i send the command in the server.
import os
import discord
import requests
import random
from discord.ext import commands
client = discord.Client()
@client.event
async def on_ready():
print('online {0.user}'.format(client))
bot = discord.ext.commands.Bot(command_prefix = "$");
@bot.command(name='filetxt')
async def filetxtgetter(ctx):
lines = open('file.txt').read().splitlines()
file = random.choice(lines)
await ctx.send(file)
client.run(os.environ['token'])
Solution 1:[1]
@bot.command()
async def filetxtgetter(ctx):
f=open('file.txt')
lines=f.readlines()
value = random.choice(lines)
random_line = (value.removesuffix('\n'))
await ctx.send(random_line)
This should solve your question.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shashankh_ |
