I'm currently codiing a simple IRC moderator/utility bot. I plan to have a web interface that will easily update command data and whether or not the command is enable using a MySQL database to store most of the information. It is able to connect to the database and retrieve the data correctly. However after I change a value in the database it does not update. I have tried to use .close() and .commit() or enabling auto commit (even though im not changing anything in the database) as solutions from others who have had this problem before.
import socket
import StringIO
import MySQLdb
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "irc.twitch.tv"
channel = "#jusjoe99"
botName = "N0tABot"
oauth = ""
twitter = {"msg": "Check me out on me out on my Twitter to stay up to date and see when ill be live next! twitter.com/jusjoe99", "enabled": True}
youtube = {"msg": "Check me out on me out on the YouTubes, I dint post much but I plan to eventually doing some vids! youtube.com/jusjoe99", "enabled": True}
game = {"msg": "", "enabled":False}
resourcePack = {"msg":"", "enabled":False}
data = []
db = MySQLdb.connect(host = "localhost",user="myBot",passwd = "wHZ4VCWe2jaYxH9y",db = "mybot")
db.autocommit(True)
cursor = db.cursor()
cursor.execute("SELECT * FROM commands")
data = cursor.fetchall()
db.commit()
cursor.close()
db.close()
def MySQL():
db = MySQLdb.connect(host = "localhost",user="myBot",passwd = "wHZ4VCWe2jaYxH9y",db = "mybot")
cursor = db.cursor()
cursor.execute("SELECT * FROM commands")
data = cursor.fetchall()
db.commit()
cursor.close()
db.close()
def ping():
ircsock.send("PONG : Pong\n")
def joinChannel(chan):
ircsock.send("JOIN " + chan +"\n")
def sendMessage(chan, msg):
ircsock.send("PRIVMSG " + chan + " :" + msg + "\n")
def hello():
ircsock.send("PRIVMSG " + channel + " :Hello\n")
def start():
ircsock.connect((server, 6667))
ircsock.send("PASS " + oauth + "\r\n")
ircsock.send("USER "+ botName + botName + botName + "\r\n")
ircsock.send("NICK " + botName + "\r\n")
joinChannel(channel)
updateValues()
def getSong():
song = open("cur_song.txt","r")
cursong = song.read()
ircsock.send("PRIVMSG " + channel + " :" + "The Current song is: " + cursong + "\n")
song.close()
def updateValues():
MySQL()
checkTwitter()
checkYouTube()
checkGame()
checkResourcePack()
def checkTwitter():
twit = data[2]
print twit[1]
twitter["enabled"] = twit[1]
def checkGame():
gme = data[0]
game["msg"] = gme[2]
if gme[1] == 0:
game["enabled"] = False
else:
game["enabled"] = True
def checkResourcePack():
rp = data[1]
resourcePack["msg"] = rp[2]
if rp[1] == 0:
resourcePack["enabled"] = False
else:
resourcePack["enabled"] = True
def checkYouTube():
ytube = data[3]
if ytube[1] == 0:
youtube["enabled"] = True
else:
youtube["enabled"] = False
start()
while 1:
ircmsg = ircsock.recv(2048)
ircmsg = ircmsg.strip('\n\r')
print ircmsg
updateValues()
if ircmsg.find(":!song") !=-1:
getSong()
if ircmsg.find(":!twitter") !=-1 and twitter["enabled"]:
sendMessage(channel, twitter["msg"])
if ircmsg.find("PING :") != -1:
ping()
if ircmsg.find(":!youtube") !=-1 and youtube["enabled"]:
sendMessage(channel, youtube["msg"])
if ircmsg.find("!tp") !=-1 and resourcePack["enabled"]:
sendMessage(channel, resourcePack["msg"])
Thank you for your help!(And i am sorry for the messiness of my code)
Related
Hello i'm trying to force client to try reconnect to server when its offline when im using localhost it works but if try it with server on linode client starts to printing new blank lines in terminal.
client code:
def main():
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect():
try:
serverSocket.connect(("IP HERE", 8000))
except:
print("connection error trying again in 10 seconds")
sleep(10)
connect()
connect()
print("Available sessions: ")
print(serverSocket.recv(1024).decode("utf-8"))
state["inputCondition"] = threading.Condition()
state["sendMessageLock"] = threading.Lock()
state["username"] = pcname
state["groupname"] = pcname + "' " + "session"
state["alive"] = False
state["joinDisconnect"] = False
state["inputMessage"] = True
serverSocket.send(bytes(state["username"], "utf-8"))
serverSocket.recv(1024)
serverSocket.send(bytes(state["groupname"], "utf-8"))
response = serverSocket.recv(1024).decode("utf-8")
if response == "/adminReady":
print("You have created the group", state["groupname"], "and are now an admin.")
state["alive"] = True
elif response == "/ready":
print("You have joined the group", state["groupname"])
state["alive"] = True
serverListenThread = threading.Thread(target=serverListen, args=(serverSocket,))
while True:
if state["alive"] or state["joinDisconnect"]:
break
if state["alive"]:
serverListenThread.start()
server code:
def handshake(client):
if len(agroups) > 0:
gr = " "
for x in agroups:
gr += "\n" + x
client.send(bytes(gr, "utf-8"))
else:
client.send(bytes("no sessions available.", "utf-8"))
username = client.recv(1024).decode("utf-8")
client.send(b"/sendGroupname")
groupname = client.recv(1024).decode("utf-8")
if groupname in groups:
groups[groupname].connect(username, client)
client.send(b"/ready")
print("User Connected:", username, "| Group:", groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
else:
groups[groupname] = Group(username, client)
agroups.append(groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
client.send(b"/adminReady")
print("New Group:", groupname, "| Admin:", username)
def main():
listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listenSocket.bind(("localhost", 8000))
listenSocket.listen(10)
print("PyRaT Server running")
while True:
client, _ = listenSocket.accept()
threading.Thread(target=handshake, args=(client,)).start()
def handshake(client):
if len(agroups) > 0:
gr = " "
for x in agroups:
gr += "\n" + x
client.send(bytes(gr, "utf-8"))
else:
client.send(bytes("no sessions available.", "utf-8"))
username = client.recv(1024).decode("utf-8")
client.send(b"/sendGroupname")
groupname = client.recv(1024).decode("utf-8")
if groupname in groups:
groups[groupname].connect(username, client)
client.send(b"/ready")
print("User Connected:", username, "| Group:", groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
else:
groups[groupname] = Group(username, client)
agroups.append(groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
client.send(b"/adminReady")
print("New Group:", groupname, "| Admin:", username)
def main():
listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listenSocket.bind(("IP HERE", 8000))
listenSocket.listen(10)
print("PyRaT Server running")
while True:
client, _ = listenSocket.accept()
threading.Thread(target=handshake, args=(client,)).start()
I dont know what to try next coz i spend writing it past 2 hours so please help
I have set up the below in Apache Airflow Admin --> Connections.
How do I read these values programmatically inside my DAG?
def check_email_requests():
conn = Connection(conn_id="artnpics_api_calls")
print(conn)
hostname = conn.host
login_name = conn.login
login_password = conn.password
port_number = conn.port
print("hostname = " + hostname + "; Login name: " + login_name + "; password = " + login_password + " ; port number = " + port_number)
request_api = hostname + ":" + port_number
print("request api " + request_api)
result = requests.get(request_api, auth=(login_name, login_password)).json()
print(result)
print("done with check_email_requests")
return False
The above obviously did not work, and I couldn't find any information on how to read from the connections (there is numerous article on how to create one programmatically). My objective is to read API connection and authentication information programmatically and invoke the call, rather than hard coding them.
Rhonald
You can do:
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection("artnpics_api_calls")
hostname = conn.host
login_name = conn.login
login_password = conn.password
port_number = conn.port
I am trying to make my IRC bot handle multiple messages at a time, but it's not sending back messages.
Behavior: Process(target=func) is called, func() calls a function that has socket.socket().send(message) in it, but the message doesn't send. Suspect is that the socket isn't passed to the sending function.
Code:
import socket
import re
import requests
import urllib
import config # just my file of variables
import math
import time
import sys
import winsound
import string
import random
import multiprocessing
# import traceback
# CONNECTION COMMANDS
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = config.server # Server
password = config.password # Password
botnick = config.botnick # Your bots nick
adminname = config.adminname # Your IRC nickname
exitcode = config.exitcode
ircsock.settimeout(300)
def connection(host, port, password, nick, realname):
ircsock.connect((host, port))
ircsock.send(bytes("PASS " + password + "\n", "UTF-8"))
ircsock.send(bytes("USER " + botnick + " " + botnick + " " + botnick + " " + botnick + "\n", "UTF-8"))
ircsock.send(bytes("NICK " + botnick + "\n", "UTF-8"))
def ping(): # respond to server Pings.
ircsock.send(bytes("PONG :pingis\n", "UTF-8"))
print("Ponged after " + str(time.time() - last_ping) + " seconds from last ping!")
def sendmsg(msg, target): # sends messages to the target.
# it enters here, no problem
ircsock.send(bytes("PRIVMSG " + target + " :" + msg + "\n", "UTF-8")) ### At this point, when using multiprocessing, the bot fails ###
print("Sending: [" + str(msg) + "] to: " + str(target))
# MAIN
if __name__ == '__main__':
connection(server, 6667, password, botnick, botnick)
# joinchan(channel)
while 1:
# print("Connected!")
ircmsg = ircsock.recv(1024).decode("UTF-8")
ircmsg = ircmsg.strip('\n\r')
if ircmsg.find("PRIVMSG") != -1:
try:
# “:[Nick]!~[hostname]#[IP Address] PRIVMSG [channel] :[message]”
name = ircmsg.split('PRIVMSG', 1)[0].split(':')[-1].split("!")[0] # ircmsg.split('!', 1)[0][1:]
message = ircmsg.split('PRIVMSG', 1)[1].split(':', 1)[1].splitlines()[0] # .strip()[0]
me = ircmsg.split('PRIVMSG', 1)[1].split(':', 1)[0].split()[0]
# print(me)
print("name: " + name + ", message: " + message)
if len(name) < 17:
if me == botnick:
if message.find("Hi!") != -1:
process1 = multiprocessing.Process(target=sendmsg, args=("Hello!", name))
process1.daemon = True
process1.start()
if name.lower() == adminname.lower() and message.rstrip() == exitcode:
sendmsg("Bot is quitting.", name)
ircsock.send(bytes("QUIT \n", "UTF-8"))
sys.exit()
time.sleep(1)
except:
pass
elif ircmsg.find("PING") != -1:
ping()
Please word your answers as simply as possible, since I am not that experienced in Python. The code above can be run with a correct config.py file.
Format:
password = "" # password to open the server
exitcode = "" # What is typed to stop the bot
server = "" # Server
botnick = "" # Your bots nick
adminname = "" # Your IRC nickname
I have a script that alerts me by mail when a phrase changes on a web page. I tried many things, but I can't fix the isAvailable() function: the script says "not available" every time, whether or not I give it an available server. Have you any clues?
# CONFIG
TARGET_KIMSUFI_ID = "160sk1" # something like 160sk1
TARGET_DESCR = ""
EMAIL_FROM_ADDRS = ""
EMAIL_TO_ADRS = ""
EMAIL_SMTP_LOGIN = EMAIL_FROM_ADDRS
EMAIL_SMTP_PASSWD = ""
EMAIL_SMTP_SERVER = ""
# CODE
import urllib.request
import smtplib
import time
def isAvailable():
rawPageContent = urllib.request.urlopen("https://www.kimsufi.com/en/servers.xml").read()
rawPageContent = str(rawPageContent)
poz = rawPageContent.find(TARGET_KIMSUFI_ID)
row = rawPageContent[poz:]
poz = row.find("</tr>")
row = row[:poz]
searchText = "Currently being replenished"
poz = row.find(searchText)
return poz != -1
def sendEmailWithMessageAvailable():
msg = "From: KIMSUFI HUNTER <"+EMAIL_FROM_ADDRS+">\r\n"+\
"To: "+EMAIL_TO_ADRS+"\r\n"+\
"Subject: [KIMSUFI] "+TARGET_DESCR+" is now AVAILABLE!\r\n"+\
"\r\n"+\
"kimsufi-hunter.py has detected that "+TARGET_DESCR+" is now ["+time.ctime()+"] available!\r\n"+\
"https://www.kimsufi.com/en/\r\n"
server = smtplib.SMTP(EMAIL_SMTP_SERVER)
server.starttls()
server.login(EMAIL_SMTP_LOGIN,EMAIL_SMTP_PASSWD)
server.sendmail(EMAIL_FROM_ADDRS, EMAIL_TO_ADRS, msg)
server.quit()
while True:
if isAvailable():
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" not available")
nextSleep = 5 #5secs
else:
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" AVAILABLE!!! -- sleeping for 5 minutes")
sendEmailWithMessageAvailable()
nextSleep = 5*60 #5mins
time.sleep(nextSleep)
Your isAvailable() function returns True if the website is available, False otherwise. You should change the if statement to:
if not isAvailable():
...
I wrote a simple Python twitch bot following a video tutorial, but the tutorial didn't include whisper functionality. It can currently connect to the chat of the channel I specify, but when I try to have it send a whisper nothing happens. Here's the relevant code bits:
import socket
def openSocket():
s = socket.socket()
s.connect((HOST, PORT))
message = "PASS " + PASS + "\r\n"
s.send(message.encode('utf-8'))
message = "NICK " + USER + "\r\n"
s.send(message.encode('utf-8'))
message = "JOIN #" + CHAN + "\r\n"
s.send(message.encode('utf-8'))
return s
def sendMessage(s, message):
messageTemp = "PRIVMSG #" + CHAN + " :" + message + "\r\n"
s.send(messageTemp.encode('utf-8'))
print("Sent:" + messageTemp)
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG #jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))
import string
from Socket import sendMessage
def joinRoom(s):
readbuffer = ""
Loading = True
while Loading:
readbuffer = readbuffer + s.recv(1024).decode()
temp = readbuffer.split('\n')
readbuffer = temp.pop()
for line in temp:
print(line)
Loading = loadingComplete(line)
def loadingComplete(line):
if("End of /NAMES list" in line):
return False;
else: return True
I've been reading a little bit about connecting to some sort of group chat in order to make this work, but I'm confused and haven't found what I'm looking for. It seems like it should be an easy fix. Any help is appreciated.
You were very close. Where you messed up is there should not be a # in front of jtv:
def sendWhisper(s, user, message):
messageTemp = "PRIVMSG jtv :/w " + user + " " + message
s.send(messageTemp.encode('utf-8'))