I'm new to python and was working on a discord bot with Discord.py. I was trying to make it so when you type %quote it would get a random line from a text file. but for some reason it skips the first line or two. maybe I'm getting the logic wrong? here's my code.
#commands.command()
async def quote(self, ctx, Qnum='janfol91213sdf2uieh1あ2Ⅳ3sんksnaaksd'):
i = 0
if Qnum == 'janfol91213sdf2uieh1あ2Ⅳ3sんksnaaksd':
f = open("cogs\Base\data\Quotes.txt")
random_lines = random.choice(f.readlines())
await ctx.send(random_lines)
else:
f = open("cogs\Base\data\Quotes.txt")
for line in f:
if i == int(Qnum):
quote = f.readline()
f.close()
break
else:
i = i+1
await ctx.channel.send(quote)
f.close()
the random Qnum thing is for optional parameter or something
Assuming your txt file looks something like this:
quote1
quote2
you could read the txt file and split it with \n, like this:
import random
with open('file.txt', 'r') as f:
read = f.read()
array = read.split('\n')
quote = random.choice(array)
await ctx.channel.send(quote)
to make sure it doesnt skip any lines, you can print the array with the quotes to the console, with print(array)
Related
i tried to make auto check if file is modified then print and send to discord using webhook, but it print the last line and before the last line. i just want to print the last line. here is the code
def readfile():
with open("test.txt", "r") as t:
read = t.readlines()
return read
before = readfile()
while True:
after = readfile()
if before != after:
for line in after:
if line not in before:
print(line)
sendembed()
before = after
im new to python, anyone can help me?
given that the first part is answered with the link: How do I watch a file for changes?
This will answer the second part, which the question was close on.
def readfile():
with open(`\test.txt`, "r") as t:
read = t.readlines()
return read
x = readfile()
# this is the last line
print( x[-1] )
The reason for this is that readlines() creates a list and the user can access the last element of the list.
so im trying to create a simple economy bot in discord.py, i want there to be a work command very similar to unbelievaboat, my idea was "if a text file 'time' doesnt exist create one, if it does then move on" and each time you ran the cmd it would save your user id to a text file, so when you run it again it would check to see if your ID was in there, if not it would let you run the command, if it was in the txt file it would halt the command and send an error message, heres the code snippet, as for the issue im facing it doesnt halt the command even though my ID was appended to the text file!::
async def work(ctx):
status = False
if not os.path.isfile("time.txt"):
with open("time.txt", "w") as f:
f.close()
with open("time.txt", "r") as f:
lines = f.readlines()
pattern = f"{ctx.message.author.id}"
for line in lines:
if pattern in lines:
status = True
else:
status = False
#with open("db.json", "r") as f:
# data = json.load(f)
if status == False:
possible = [40, 50, 15, 20, 80]
amount = random.choice(possible)
if not os.path.isfile(f"{ctx.message.author.id}.txt"):
with open(f"{ctx.message.author.id}.txt", "w") as f:
f.write(f'0')
f.close()
with open(f"{ctx.message.author.id}.txt", "r") as f:
current_bal = int(f.read())
sum = current_bal + int(amount)
print(sum)
with open(f"{ctx.message.author.id}.txt", "w") as f:
f.write(str(sum))
with open("time.txt", "a") as f:
f.write(f"{ctx.message.author.id}\n")
f.close()
embed = discord.Embed(title=f"✅ {ctx.message.author.name} worked", description=f"You worked for hours and earned {amount} :{emojiname}:")
await ctx.channel.send(embed=embed)
else:
embed = discord.Embed(title=f"Error!", description=f"You cant work yet! default wait time is 5m!")
await ctx.channel.send(embed=embed)
Any ideas or suggestions i can use to improve my code or solve my issue?
How can I add value to an existing list of YAML files using the discord.py command?
here's what I've tried:
#bot.command()
async def addwhitelist(ctx, id : int=None):
with open("./config.yml", "r") as file:
data = file.readlines()
data[0][49] = f", {id}"
with open("./config.yml", "w") as file:
file.writelines(data)
file.close()
and here's what's the list:
Whitelist: [483686172221243402, 740936250608844890]
NOTE: I want it to add more than once so whenever I want to add a new value to that list.
so how can I do that?
You should probably use the pyyaml library:
import yaml
#bot.command()
async def addwhitelist(ctx, id):
with open('./config.yml', 'r') as f:
conf = yaml.safe_load(f)
conf['Whitelist'].append(id)
with open('./config.yml', 'w') as f:
yaml.dump(conf, f)
The usage of discord.py here is irrelevant.
So if I understand correctly, you have a YAML file where the first line looks like Whitelist: [483686172221243402, 740936250608844890].
You want to be able to add new numbers to this list. So for example adding a new number 83298234892891392 inside the list, while keeping the other numbers there.
To do this, I would do:
def whitelist(id: int):
with open("./config.yml", "r") as file:
lines = tuple(file)
lines[0].removeprefix('Whitelist: ')
whitelist = eval(lines[0])
whitelist.append(id)
lines[0] = 'Whitelist: ' + str(whitelist)
with open("./config.yml", "w") as file:
for line in lines:
file.write(line)
I created a notepad text document called "connections.txt". I need to have some initial information inside it, several lines of just URLs. Each URL has it's own line. I put that in manually. Then in my program I have a function that checks if a URL is in the file:
def checkfile(string):
datafile = file(f)
for line in datafile:
if string in line:
return True
return False
where f is declared at the beginning of the program:
f = "D:\connections.txt"
Then I tried to write to the document like this:
file = open(f, "w")
if checkfile(user) == False:
usernames.append(user)
file.write("\n")
file.write(user)
file.close()
but it hasn't really been working correctly..I'm not sure what's wrong..am I doing it wrong?
I want the information in the notepad document to stay there ACROSS runs of the program. I want it to build up.
Thanks.
EDIT: I found something wrong... It needs to be file = f, not datafile = file(f)
But the problem is... It clears the text document every time I rerun the program.
f = "D:\connections.txt"
usernames = []
def checkfile(string):
file = f
for line in file:
if string in line:
return True
print "True"
return False
print "False"
file = open(f, "w")
user = "aasdf"
if checkfile(user) == False:
usernames.append(user)
file.write("\n")
file.write(user)
file.close()
I was working with the file command incorrectly...here is the code that works.
f = "D:\connections.txt"
usernames = []
def checkfile(string):
datafile = file(f)
for line in datafile:
if string in line:
print "True"
return True
print "False"
return False
user = "asdf"
if checkfile(user) == False:
usernames.append(user)
with open(f, "a") as myfile:
myfile.write("\n")
myfile.write(user)
The code that checks for a specific URL is ok!
If the problem is not erasing everything:
To write to the document without erasing everything you have to use the .seek() method:
file = open("D:\connections.txt", "w")
# The .seek() method sets the cursor to the wanted position
# seek(offset, [whence]) where:
# offset = 2 is relative to the end of file
# read more here: http://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek
file.seek(2)
file.write("*The URL you want to write*")
Implemented on your code will be something like:
def checkfile(URL):
# your own function as it is...
if checkfile(URL) == False:
file = open("D:\connections.txt", "w")
file.seek(2)
file.write(URL)
file.close()
hello all im trying to read text file line by line and then store all the data into an array and i want to add text in the value of array such as
admin
administrator
adm
log
login
after got this lines i want to add (.php)
in the end of it
and this is my code
current_folder= os.path.dirname(os.path.realpath(__file__))
current_list=str(current_folder)+"\pages.txt"
ins = open( current_list, "r" )
array = []
for line in ins:
array.append(line.rstrip())
for fahad in array:
array+".php"
This code:
try:
with open('test.txt', 'r') as ins: #Opens the file and closes it when Python is done with it
array = []
for line in ins:
array.append(line.rstrip()) # appends each line of the file with trailing white space stripped
for fahad in array:
fahad += ".php" # for each item in the list 'array' it concatenates '.php' on to the end. The += operator is the same as fahad = fahad + '.php'
print(fahad)
except FileNotFoundError: # this is part of a try/except block. If the file isn't found instead of throwing an error this will trigger. Right now nothing happens because of the pass statement but you can change that to print something if you like.
pass
produces:
>>> fahad
'admin administrator adm log login.php'
I guess this should work.
current_folder= os.path.dirname(os.path.realpath(__file__))
current_list=str(current_folder)+"\pages.txt"
ins = open( current_list, "r" ).read().split()
array = []
for line in ins:
array.append(line + ".php")
You could try this code:
ins = open( "hello.txt", "r" )
array = []
rows = ins.read().split('\n') #or \r\n - it depends from your txt
for row in rows:
array.append(row+".php")
ins.close()