I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)
Related
I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.
Im working on chatbot where bot ask users name and then bot replies with Greeting + name. This works when I use this on terminal with input() but not able to figure out how to accept input from slack and use that input.
def start(request, channel):
response = ('\n\nHello!')
send_response(response, channel)
name = ('Please tell me your name.\n')
send_response(name, channel)
name = request
greet = "Hello" + name
send_response(greet, channel)
def send_response(response,channel):
slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def parse_slack_output(slack_rtm_output):
output_list = slack_rtm_output
if output_list and len(output_list) > 0:
for output in output_list:
if output and 'text' in output and AT_BOT in output['text']:
# return text after the # mention, whitespace removed
return output['text'].split(AT_BOT)[1].strip(), \
output['channel']
return None, None
if __name__ == "__main__":
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
if slack_client.rtm_connect():
print ("connected and running!")
while True:
request, channel = parse_slack_output(slack_client.rtm_read())
if request and channel:
start(request, channel)
time.sleep(READ_WEBSOCKET_DELAY)
else:
print("Connection failed. Invalid Slack token or bot ID?")
As per slack doc, dialog.open() method is the way to achieve your requirement.
https://api.slack.com/dialogs.
EDIT:
And RASA NLU-CORE gives more option for conversational based ChatBots. http://rasa.com/docs/core/quickstart/
Slot Filling is what you need to look into to store the name or any other values and use it further in the conversation.
I have the following piece of Python 2.7 code:
def getGateway():
""" Use the configuration to determine valid gateway
If more GWs are present, one will be chosen by random.choice
"""
localServer = ThisLocalServer(log=LOG)
gw=localServer.getRandomAgentGateway()
print "See if its a string %s - %s" % (gw,type(gw))
candidate = "gw"
response = os.system("ping -c 1 " + candidate)
if response == 0:
print candidate, 'is up!'
return gw
else:
print candidate, 'is down we need a new gatewuy'
The use case is as follows:
My software determines an IP using getRandomAgentGateway. Unfortunately it is not as inteligent as i want it to be and sometimes the result is an unreachable IP. I want to build in a ping check that will :
A) Get one IP ( there are only two in the list ) using the already built in getRandomAgentGateway
B) Ping the IP
C) Make sure this IP is reachable , if yes - deliver a reachable IP, break out of the loop and execute "return gw" , if not - stay in the loop and call "getRandomAgentGateway()" again until it finds a reachable IP
I cannot modify getRandomAgentGateway, so i would like to build the ping check here. Any assistance will be highly appreciated.
It seems that you have an error in your logic.
candidate = "gw"
seems to be doing the wrong thing. What you need is probably
if isinstance(gw,str):
# do whatever
Actually, why getRandomAgentGateway will return other answer than an str?
Finally, for this to work you probably should try more than one time, writing something like:
def teste():
max_number_of_tries = 2
current_try = 0
while current_try < max_number_of_tries:
gw=getRandomAgentGateway()
if isinstance(gw,str):
response = os.system("ping " + gw)
if response == 0:
print( gw, 'is up!')
return gw
else:
print( gw, 'is down we need a new gatewuy, trying again')
current_try += 1
print ( "Too much tries" )
so far I have this:
import datetime
f = open("log.txt", "a", encoding='UTF-8')
print ("Log file created")
print ("Enter /close to leave.")
spc = " "
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg == None:
pass
if msg == " ":
pass
else:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
However, this line is not functioning as I want it, it still returns a blank line on the log file:
if msg == None:
pass
I want it to not return anything and simply continue the while loop, How would I fix this?
You should be using
if msg is None:
pass
Edit
You're missing what the pass function is all about. I would re-write your look like so. This way we're only processing this if the msg is not one of the bad input. Once we're done we break out of the loop.
...
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if not msg in [None, " "]
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
break
Evaluation of the rest of the loop will still continue after pass, and as None does not equal " ", this means the block beginning with msg2 = now1+spc+msg+"\n" will be executed. You need to either unite the if ... if ... else into a single if block by changing if msg == " ": to elif msg == " ": or else change if msg == None: pass to if msg == None: continue.
try:
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
except:
pass #example for a function: return None or raise
Your condition doesn't make any sense. The input function will never return None, only strings.
If you want to skip empty strings, a better test would be if not msg (empty strings are "falsy"). Or, if you want to reject any all-whitespace strings, try if not msg.strip() (which removes leading and trailing whitespace before checking if the rest of the string is empty or not).
Further, it's rarely a good idea to write an if statement that just contains pass. Instead, invert the test so that the condition is true for cases where you want to run some code (in this case, when msg is not empty or all whitespace) and simply omit the cases where you'd do nothing:
while 1:
msg = input(">>:")
now = datetime.datetime.now()
now1 = str(now)
if msg.strip(): # msg is not empty or all whitespace
msg2 = now1+spc+msg+"\n"
if msg == "/close":
exit()
f.write(msg2)
f.flush()
One final issue (unrelated to the main question). Python's exit function is primarily intended for use in the interactive interpreter. It is added to the builtins by the site module, and so it won't exist if Python was run with the -S flag. If you want to close the interpreter, you should instead call sys.exit, raise a SystemExit exception, or just run off the end of the main module (a break statement would probably do that for the loop you've shown here, or perhaps a return if you're in a function somewhere).
This code stopped doing anything at all after I changed something that I no longer remember
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv()
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
edit: Lol sorry guys forgot to say its supposed to run the input
You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit'. Which is won't, because you are just using input(), not raw_input(), so the person would have to enter 'exit' (including quotes) or else the loop will never exit. (Assuming it's not Python 3 Code)
It's doing nothing because there's no code to make it do anything. Try inserting a line like
print("You entered:", userinput)
at an appropriate place in your loop.
os.getenv() must have at least one param. Try os.getenv("HOST") or something.