chatterbot: def handler(msg) - Chatbot doesn't recognize my Telegram ID - python

I decided for my test chatbot on Telegram to create a function to limit the ability to speak only to a few users. I thought to create a .csv to put the Telegram user ID (the file is in the program folder). However, when I go to start the chat or write with my bot, I get the non-acknowledgment message ("I don't talk with strangers, dear ") with my ID Telegram. But I already put it in the file! So, I tried to see the data of chat with the Telegram API "getUpdate", but it doesn't appear ( {"ok":true,"result":[]} ).
This is my function:
`def handle(msg):
global bot
global chatter
global language
chat_id = msg['chat']['id']
sender = msg['from']['id']
users = listusers()
if checkuserid == 1:
verified = 0
if users != "":
for usr in users:
if str(sender) == usr:
verified = 1
if verified == 0:
bot.sendMessage(chat_id, "I don't talk with strangers, dear "+str(sender))
#write this user in the list of attempted accesses
if attemptsfile != '':
lines = ''
if os.path.isfile(attemptsfile):
text_file = open(attemptsfile, "r")
lines = text_file.read()
text_file.close()
lines = lines + str(datetime.datetime.now()) + " --- UserdID: " + str(sender) + " DENIED \n"
text_file = open(attemptsfile, "w")
text_file.write(lines)
text_file.close()
return
command = ''
try:
if msg['text'] != '':
command = msg['text']
print('Got command: ' + command)
except:
print("No text in this message")
if command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
elif '/adduser' in command:
if len(command.split(' ')) > 1:
usrname = command.split(' ')[1]
adduser(usrname)
bot.sendMessage(chat_id, "User "+usrname+" added")
elif '/deluser' in command:
if len(command.split(' ')) > 1:
usrname = command.split(' ')[1]
deluser(usrname)
bot.sendMessage(chat_id, "User "+usrname+" deleted")
elif command == '/help':
bot.sendMessage(chat_id, "/adduser /deluser /time /exit")
elif command == '/exit':
global active
active = False
bot.sendMessage(chat_id, "The bot will shutdown in 10 seconds")
elif command != '':
answer = chatter.reply(command)
bot.sendMessage(chat_id, str(answer))
`

Related

Errno 2 No such file or directory "I get this error even with one line of code that should work"

I'm just starting with python and I want to make a simple login system with text files. Everytime I run the code I get this error. It doesn't even make the text file. Before this, I could run my code and it made a file but now it doesn't. I tried just one line of code to open a text file but that doesn't work either.(line of code: f = open("demofile.txt")) I also tried to google it, no solution. I don't know what to do?
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
f = open("dataBank.txt", 'w')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if name in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
i dont know whats your logic but to create a file you need to use a w+
try it by de the code
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
try:
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
except:
return 'Data base donest exists. creating one...'
f = open("dataBank.txt", 'w+')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if username in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
The error you get in f = open('demofile.txt') is because open takes an additional argument 'mode' whose default value is 'r' for read. If the passed filename does not exist you get the described error.
Use f = open('demofile.txt','w') instead for writing to a file. This creates a new file if the filename does not exist.

How to make a separate "timer-like" function to set a variable, while the main loop keeps running?

I'm trying to write a Python script, the main function of the code is a while loop always looking for a keyword, and when the keyword is found, it'll exit the script.
import telepot
import datetime
import time
bot = telepot.Bot('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
print ('start listening to replies')
last_update = 0
update_offset = 0
f = open('last_update_id.txt', 'r')
if f == '':
last_update = 0
elif type(f) == str:
last_update = int(f)
elif type (f) == int:
last_update = f
f.close
update_offset = last_update + 1
#START LOOP UNTIL SATISFIED WITH REPLY
while true:
#get update
response = bot.getUpdates(offset=update_offset)
listOfSenders = []
for i in response:
#INTERPRETION OF CURRENT MESSAGE
update_id = i['update_id']
message = i['message']
whoSent = message['from']
senderUsername = whoSent['username']
timestampEpoch = message['date']
timestampHuman = datetime.datetime.fromtimestamp(timestampEpoch).strftime('%Y-%m-%d %H:%M:%S')
text = message['text']
print(text + ' from ' + sender + ' at ' + timestampHuman + ' server\'s time')
listOfSenders.append(senderUsername)
#TAKE ACTION TO MESSAGE
#is boss here?
if 'boss' in listOfSender:
bossIsPresent = 'yes'
else:
bossIsPresent = 'no'
if 'done' in text:
#job is done, bye
jobDone = 'yes'
else:
jobDone = 'no'
if bossIsPresent = 'yes':
bot.sendMessage(zzzzzzz, 'My boss is here. Goodbye')
#boss not here, reply
elif jobDone = 'yes':
bot.sendMessage(zzzzzzz, 'OK. My Job is done. Goodbye')
#write last update_id to file
f = open('last_update_id.txt', 'w+')
f.write(str(update_id))
f.close
#exit
exit
elif jobDone = 'no':
bot.sendMessage(zzzzzzzz, 'Huh?!')
#PREPARE FOR NEXT UPDATE
#the next update_offset
update_offset = update_id + 1
time.sleep(10)
#write last update_id to file
f = open('last_update_id.txt', 'w+')
f.write(str(update_id))
f.close
What I'm trying to achieve is, as long as boss has replied in the past five minutes, the bot replies nothing, after the five minutes ran out, then the bot will reply "Boss is not here". And every time boss replies, it'll reset the five minutes. But at any time it should be detecting for 'done'. How do I do this?

How to print weather information to the console in python

I'm currently creating a text based console program in python and I want to add a command to display the current weather using a zip code. I have tried googling it extensively and can't seem to find anything good. The solutions that would work for what I'm trying to do are all using technology I'm not familiar with that are used to make actual apps with python. There is currently no UI and I'm a beginner in python so the more readable and easily understandable the solution the better.
#import statements
import math#import math
import os#access the operating system
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
import time
#end import statement
# welcome user
print("welcome to geeko an all in one desktop helper!")
#end welcome
#variables
username = input("Please enter your username: " )#gets username
sudo = False # sets sudo to false indicating normal privledges
if (username == "Caelin"): # if the user enters the sudo username prompt them for a password
sudoPassword = input("enter sudo password: ")# prompt for passcode
sudoLn = False #sets sudo line mode to false. this line mode is used for sudo commands
pi = math.pi
loc_id = 'USAL0504'
def wrongLineError():
if(sudoLn):
print("You are on the sudo line this is purely for special commands normal commands don't work here type \"switch\" to switch to cmd.ln")
elif(sudoLn == False and sudo == False):
print("You do not have sudo priviledges")
elif(sudoLn == False and sudo == True):
print("to use sudo commands you must be on the sudo line mode type \'switch\' to switch to the sudo line")
def sendEmailMessageOnly(message, password, recipient):
send_to_email = recipient # Who you are sending the message to
server = smtplib.SMTP('smtp.gmail.com', 587) # Connect to the server
server.starttls() # Use TLS
server.login(email, password) # Login to the email server
server.sendmail(email, send_to_email , message) # Send the email
server.quit() # Logout of the email server
def sendFormattedEmail(password, recipient, subject, message):
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipient, text)
server.quit()
def sendMultipleFormattedEmails(password, recipients, subject, message):
for recipientEmail in recipients:
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipientEmail
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipientEmail, text)
server.quit()
#end variables
print ("Hello " + username + "!")# say special welcome
#check if user is root if so alert them and give them sudo status else alert them and leave sudo at a default of false
if(username == "Caelin" and sudoPassword == "bigGlassRemote"):
print("Welcome! you are the root user and therefore have elevated priviledges")
email = input('please enter your email: ')
password = input("please enter your email password: ")
print('logging into email...')
time.sleep(1)
print("logged into email!")
sudo = True
else:
print("You are not the root user and have normal priviledges")
while(True): #run an infinite loop prompting the user for command line inputs
if(sudoLn == False):
command = input(username + "-cmd.ln: ") # if sudo line mode if off use the cmd.ln prompt
else:
command = input(username + "-cmd.sudo: ") # otherwise prompt with cmd.sudo to indicate you are using sudo line mode
if(command == 'welcome'):
if(sudoLn == False): # checks if you are on cmd line
print("Hello " + username) # if the welcome command is used say hello *username*
else: # if you are the sudo line
wrongLineError()
elif(command == "switch"): # if the command is switch
if(sudo): # then check for sudo priviledges
# togles sudoLn
if(sudoLn):
sudoLn = False
else:
sudoLn = True
else:
wrongLineError()
elif(command == 'add'):
if(sudoLn == False):
num1 = input("type the first number to add here: ")
num2 = input("type the second number to add here: ")
ans = float(num1) + float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == 'subtract'):
if(sudoLn == False):
num1 = input("type the first number to subtract here: ")
num2 = input("type the second number to subtract here: ")
ans = float(num1) - float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "multiply"):
if(sudoLn == False):
num1 = input("type the first number to multiply here: ")
num2 = input("type the second number to multiply here: ")
ans = float(num1) * float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "divide"):
if(sudoLn == False):
num1 = input("type the first number to divide here: ")
num2 = input("type the second number to divide here: ")
ans = float(num1)/float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of circle"):
if(sudoLn == False):
r = input("type the radius here: ")
ans = pi*(float(r)**2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of rectangle"):
if(sudoLn == False):
l = input("type the length here: ")
h = input("type the width here: ")
ans = float(l)*float(h)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of triangle"):
l = input("type the length here: ")
h = input ("type the height here: ")
ans = (float(l) * float(h))/2
if(ans == round(ans)):
print(int(ans))
else :
print(ans)
elif(command == 'pi'):
if(sudoln):
print(pi)
else:
wrongLineError()
elif(command == "edit file anywhere"):
if(sudoLn):
path = input("enter the path to the file (if the file doesen't exist it will be created): ")
file = open(path, "w+")
Exit = False
while(not Exit):
write = input("type what you would like to be written on the document. type !#exit to return to the the command line: ")
if(write == "!#exit"):
file.close()
Exit = True
else:
file.write(write)
else:
wrongLineError()
elif(command == "delete file anywhere"):
if(sudoLn):
path = input("enter the path to the file you wish to delete: ")
os.remove(path)
print(path + "has been removed")
else:
wrongLineError()
elif(command == 'send unformatted email'):
if(sudoLn):
recipient = input('enter the recipient\'s email address: ')
msg = input("enter the content of the email: ")
print('Sending email...')
sendEmailMessageOnly(msg, password, recipient)
print('Email sent!')
else:
wrongLineError()
elif(command == "send formatted email"):
if(sudoLn):
subject = input('enter the subject line: ')
recipient = input('enter the recipient\'s email address. type multiple to send an email to multiple recipients: ')
if(recipient == 'multiple'):
sendMultiple = True
repeat = True
i = 1
recipient = []
while(repeat):
newRecipient = input('recipient%s\'s email address. type !#continue to continue to select a message and send the email: ' % i)
if(newRecipient == '!#continue'):
repeat = False
else:
recipient.append(newRecipient)
i += 1
message = input("enter the content of the email: ")
print('Sending email...')
if(not sendMultiple):
sendFormattedEmail(password, recipient, subject, message)
else:
sendMultipleFormattedEmails(password, recipient, subject, message)
print("Email sent!")
else:
wrongLineError()
elif(command == "help"):
if(sudoLn):
print(username + """-sudo.ln command help:
>>edit file anywhere > input(s): path > Takes a file path and edits that file.
If the file doesn't already exist it is created.
If you wish to edit a file in the same location as geeko simply enter the name and leave out the path.
>>delete file anywhere > input(s): path > Takes a file path and deletes the file with that path.
If you wish to delete a file in the same location as geeko simply enter the name and leave out the path.
>>send unformatted email > input(s): recipient, message > Sends an email to the recipient containing the message you entered.
>> send formatted email > input(s): recipient, subject line, message > Sends an email to the recipient with the entered subject line and message.
This also enters To and From information into the email.
>>help > no inputs > Shows this help message.
A different message is shown for cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-sudo.ln HELP""" % username)
else:
print(username + """-cmd.ln command help:
>>add > input(s): first number, second number > Adds two numbers together.
>>subtract > input(s): first number, second number > Subtracts the second number from the first number.
>>multiply > input(s): first number, second number > Multiplies the two numbers together.
>>divide > input(s): first number, second number > Divides the first number by the second number.
>>area of rectangle > input(s): length, width > Calculates the area of a rectangle with the given length and width.
>>area of triangle > input(s): length, height > Calculates the area of a triangle with the given length and height.
>>area of circle > input(s): radius > Calculates the area of a triangle with the given radius.
>>pi > no inputs > Prints the first 16 digits of pi
>>welcome > no inputs > Gives you a special welcome.
>>print reversed sentence > input(s): sentence > Prints the sentence backwards.
>>help > no inputs > Shows this help message.
The help message is different in cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-cmd.ln HELP""" % username )
elif(command == 'print reversed sentence'):
sentence = input("enter the senctence you want to reverse: ")
sentence = sentence[::-1]
print(sentence)
elif(command == 'weather'):
get_weather(loc_id)
elif(command == "close"):
confirmedOrDenied = False
while(not confirmedOrDenied):
confirmation = input("are you sure you want to close geeko [Y/N]: ")
if(confirmation == 'y' or confirmation == 'Y'):
exit()
elif(confirmation == 'n' or confirmation == 'N'):
confirmedOrDenied = True
print("cancelled")
else:
print('invalid response please enter Y or N')
else:
print(command + ' is not a valid command make sure everything is spelled correctly') # if no registered command was entered return invalid command
There are 2 main ways to do this.
The first one is to webscrape, using requests and beautifulsoup4. This can most easily be done from google, since if you search "weather {city-name}" it gives you a summary of the weather there.
The second is to use an api such as openweathermap, for which there is a great geeksforgeeks tutorial on:

IRC Twitch somehow start ignoring messages

I'm just trying to make a 'Twitch Plays' game. I used a tutorial for making Twitch Plays games. I need to re-run this code every five minutes as it ignores the messages. I'm making Threes game on Scratch. I checked for all the possible bugs and it works very well. This game is based on moving tiles that contain numbers on them. Any suggestions regarding the IRC twitch ignoring all messages will be highly appreciated.
The code is shown here below.
import socket
import pyautogui
import time
SERVER = "irc.twitch.tv"
PORT = 6667
PASS = "oauth:fz5kp09su0lz46vnos78sklvpjnu6l"
BOT = "TwitchBot"
CHANNEL = "olejika2016"
OWNER = "olejika2016"
message = ""
irc = socket.socket()
irc.connect((SERVER,PORT))
irc.send(( "PASS "+PASS+"\n"+
"NICK "+BOT+"\n"+
"JOIN #"+CHANNEL+"\n").encode())
def twitch():
def joinchat():
loading = True
while loading:
readbuffer_join = irc.recv(1024)
readbuffer_join = readbuffer_join.decode()
for line in readbuffer_join.split("\n")[0:-1]:
# print(line)
loading = loadingComplete(line)
def loadingComplete(line):
if ("End of /NAMES list" in line):
print("Bot has joined "+CHANNEL+"'s channel")
sendMessage(irc, "Chat Room Joined")
return False
else:
return True
def sendMessage(irc, message):
messageTemp = "PRIVMSG #" + CHANNEL + " :" + message
irc.send((messageTemp+"\n").encode())
def getUser(line):
separate = line.split(":", 2)
user = separate[1].split("!",1)[0]
return user
def getMessage(line):
global message
try:
message = (line.split(":",2))[2]
except:
message = ""
return message
joinchat()
while True:
try:
readbuffer = irc.recv(1024).decode()
except:
readbuffer = ""
for line in readbuffer.split("\r\n"):
if line == "":
continue
else:
# print("2;"+line)
user = getUser(line)
message = getMessage(line)
print(user+":"+message)
def writeUser():
time.sleep(0.1)
pyautogui.typewrite(user)
pyautogui.press('enter')
if message.lower() == "w":
pyautogui.press('up')
writeUser()
if message.lower() == "s":
pyautogui.press('down')
writeUser()
if message.lower() == "a":
pyautogui.press('left')
writeUser()
if message.lower() == "d":
pyautogui.press('right')
writeUser()
else:
pass
user = ''
message = ''
twitch()
for line in readbuffer.split("\r\n"):
if line == "":
continue
elif "PING" is line and Console(line):
msgg = "PONG tml.twitch.tv\r\n".encode()
irc.send(msgg)
print(msgg)
continue
else:
user = getUser(line)
message = getMessage(line)
print(user+":"+message)

Returning to 'main menu' for mini email program

So for practice, I tried writing a simple program to read/write emails from the terminal/python shell. My problem is that whenever I try entering an invalid response, it ends the program rather than returning to the 'main menu,' so to speak. Same problem for when I try to give the option of quitting the program and asking the user to confirm that they want to exit. This is my code:
import smtplib
import imaplib
import email
print 'Welcome to NhuMail'
print '\n \nPlease enter your login information: \n'
user = raw_input('Email User:')
pw = raw_input("Password:")
def check_mail(user, pw):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(user, pw)
imap.select('INBOX')
# Use search(), not status()
status, response = imap.search('INBOX', '(UNSEEN)')
unread_msg_nums = response[0].split()
# Print the count of all unread messages
print '\n\nYou have %s unread messages.' % (len(unread_msg_nums))
def read_mail():
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(user, pw)
imap.list()
imap.select("inbox")
status, response = imap.search('INBOX', '(UNSEEN)')
unread_msg_nums = response[0].split()
result, data = imap.uid('search', None, "ALL") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = imap.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
email_message = email.message_from_string(raw_email)
print email_message['To']
print email.utils.parseaddr(email_message['From']) # for parsing "Yuji Tomita" <yuji#grovemade.com>
email_items = email_message.items()
# print all headers
print email_items[1]
print email_items[2]
print email_items[5]
print '\n'
b = email.message_from_string(raw_email)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
def new_mail():
from_add = user
to_add = raw_input('Enter TO address:')
msg = raw_input('Enter desired message:')
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(user,pw)
server.sendmail(from_add,to_add,msg)
def exit_mail():
confirm_exit = raw_input('Are you sure you want to exit? (Yes/No):')
server = smtplib.SMTP('smtp.gmail.com:587')
if confirm_exit == 'Yes':
server.quit()
print 'Nice Nhu-ing you! Come again soon :)'
elif confirm_exit == 'No':
return prompt
def mail_options():
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
while True:
if prompt == 'Nhu':
new_mail()
return prompt
elif prompt == 'Read':
read_mail()
return prompt
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
return prompt
check_mail(user,pw)
mail_options()
It looks like you want to keep calling mail_options(). You can do this with an infinite loop:
while True:
mail_options()
You could also put the loop inside mail_options():
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
while True:
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
Try changing your mail_options() to this:
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
You present the prompt once and then as soon as you get their result, you return what they said after running the specified function, and then because you use a return keyword, it breaks out of the loop and function and exits the program.
The issue in your program lies in mail_options(). You have an infinite loop, that can only run a single time, and then exits every time time due to the use of a return statement. Make an infinite loop to continuously show mail_options(), and it should fix your issue. You're only calling it once, which is why it exits.
You can do:
while True:
mail_options()
Another option would be asking the prompt inside the loop, and ridding the function of return statements.
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
return # Get out of the function.
else:
print 'You didn\'t enter one of the options!'

Categories

Resources