I have been working on a TwitchTV Python chat bot for a while now, but I'm still getting to grips with Python.
It may seem simple, but this has confused me so I decided I would ask:
I'm currently pulling messages from Twitch Chat using data = irc.recv
What I want to do is use the data pulled and turn it into a string, so that I can then check for capitals in the messages using str.isupper()
I've already tried a few ways;
data = irc.recv (4096)
msg = data()
capsTime = "30s"
str = msg
if str.isupper():
message("[-] Woah! Hold back on the caps! (Timeout " + capsTime + ")")
message("/timeout " + user + capsTime)
# variable "user" already defined
This is just one, that unfortunately didn't work.
EDIT:
This is my new code, It runs without error messages, but It doesn't function as I want it to;
while True:
data = irc.recv (4096)
user = data.split(':')[1]
user = user.split('!')[0]
caps = data.split(':')[0]
capsmsg = str(data)
print data
if data.find('PING') != -1:
irc.send('PONG ' + data.split()[1] + '\r\n')
if capsmsg.isupper():
message("[-] Woah! Hold back on the caps, " + user + "! (Timeout 30s)")
message("/timeout " + user + " 30s")
EDIT 2:
Expected output:
If a message is found in ALL caps, it will print this message and time the user out:
message("[-] Woah! Hold back on the caps, " + user + "! (Timeout 30s)")
Current output:
The bot does not pick the message up or run the scripted code.
Try this:
data = irc.recv (4096)
# msg = data()
capsTime = "30s"
mystr = repr(data)
if mystr.isupper():
message("[-] Woah! Hold back on the caps! (Timeout " + capsTime + ")")
message("/timeout " + user + capsTime)
# variable "user" already defined
Don't use reserved keyword.
Related
So, in my server side, I created a dict that takes records from a .txt file:
records = {}
with open("data.txt") as f:
for line in f:
(name1, age, location, number) = line.split("|")
records[str(name1)] = [age, location, number]
As of now, I am able to print this DB on the server side :
print("** Python DB contents **\n")
for keys in records.keys():
value_list = records[keys]
print(keys + "|" + value_list[0] + "|" + value_list[1] + "|" + value_list[2])
However, I want to send this to the client side, but nothing is working for me.
I have tried sending it to the client side by creating a list that contains the contents, then sending it to the client like so:
Server:
for keys in records.keys():
value_list = records[keys]
string = keys + "|" + value_list[0] + "|" + value_list[1] + "|" + value_list[2]
client.send(string.encode())
Client:
buffer = server.recv(1024).decode() # receive from server
print(f"Server: {buffer}") # print in server what was sent
Anyone know what exactly is wrong here? This is how I've been sending and receiving stuff my whole code but in this case it just does not work!
I'm asking the user for an email, and then sending it to an email verification api, which I then get certain bits of info from. I'm getting a KeyError: 'username' and I have no idea why I'm getting that error. It's also annoying to test since they ratelimit after ~5 attempts
import json, requests, sys
emailInput = ""
def printHelp():
print("Proper usage is: python test.py [email]")
if len(sys.argv) < 2:
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] == "--help":
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] != "--help":
emailInput = str(sys.argv[1])
url = 'https://api.trumail.io/v2/lookups/json?email=' + str(emailInput)
res = requests.get(url)
res.raise_for_status()
resultText = res.text
emailInfo = json.loads(resultText)
print("\nEmail Analyzer 1.0\n\nInformation for email: " + sys.argv[1])
print("=====================================================")
print("Username: " + str(emailInfo["username"]))
print("Domain: " + str(emailInfo["domain"]))
print("Valid Format: " + str(emailInfo["validFormat"]))
print("Deliverable: " + str(emailInfo["deliverable"]))
print("Full Inbox: " + str(emailInfo["fullInbox"]))
print("Host Exists: " + str(emailInfo["hostExists"]))
print("Catch All: " + str(emailInfo["catchAll"]))
print("Disposable: " + str(emailInfo["disposable"]))
print("Free: " + str(emailInfo["free"]))
The reason is because a user enters an email that might seem valid - i.e. it's a valid email address with an # symbol etc. - but the email likely does not exist or is not in use.
For example, I ran your script with the following dummy input:
emailInput = 'acdefg#gmail.com'
After I added a print(emailInfo) statement for debugging purposes, this is what I found to be the output from the server:
{'Message': 'No response received from mail server'}
Therefore, your goal here will be to validate the server output. That is, in the case of a valid email that does not exist, you will receive an HTTP 200 (OK) response from the server with a Message field alone populated in the JSON response object. The task here will be to correctly detect the presence of this key, and then run a separate logic other than the happy path, which was already being handled above.
Your error is coming from the fact that emailInfo does not have a key username. Perhaps use emailInfo.get("username", default_value), where default_value is any value you would like if there is no username.
The line with the error is print("Username: " + str(emailInfo["username"]))
So I made a Twitch.tv bot for my own channel, after having fun with it a little bit, I wanted to have some command restricted to some users, and some commands that can say the users name, for example:
Username reply example:
Person1: !tea
PythonBot: Would you like some tea, Person1?
Admin restriction example:
Person1: !ban Person2
PythonBot: I'm sorry, Person1, This command is restricted to admins only.
Ok, So here is the code I'm using (I will be modifying it soon to make it my own)
import socket
import threading
bot_owner = '~Not Today~'
nick = '~Not Today~'
channel = '~Not Today~'
server = 'irc.twitch.tv'
password = '~Not Today~'
queue = 13
irc = socket.socket()
irc.connect((server, 6667))
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
def message(msg):
global queue
queue = 5
if queue < 20:
irc.send('PRIVMSG' + channel + ' :' + msg + '\r\n')
else:
print 'Message Deleted'
def queuetimer():
global queue
queue = 0
threading.Timer(30,queuetimer).start()
queuetimer()
while True:
botdata = irc.recv(1204)
botuser = botdata.split(':')[1]
botuser = botuser.split('!')[0]
print botdata
if botdata.find('PING') != -1:
irc.send(botdata.replace('PING', 'PONG'))
if botdata.find('!res') != -1:
irc.send(botdata.replace('!res', '1600x900'))
The twitch IRC raw message is like
:jkm!jkm#jkm.tmi.twitch.tv PRIVMSG #trumpsc :needs Kappa
for above msg, it actually means userjkm at channel trumpsc saying needs Kappa
for your code, the method to get botuser is right, but you don't have the message the user sent, add following code should get the message
botmsg = botdata.split(':')[2]
so you get the message and username, the next step would be handling them.
Here would be some example for your need. For me, I will prepared a adminuserList and commmandList for other command, but I will simplify it here.
def commmanHandler(botuser, botmsg): # botmsg = '!ban user1'
command = botmsg.split(' ')[0] # command = '!ban'
command = command[1:] # command = 'ban'
argu = message.split(' ')[1] # argu = 'user1'
if command not in commmandList:
raise Exception("command not support")
if command == 'ban': # ban command, or using switch
# check if admin
if botuser not in adminList:
raise Exception("I'm sorry, " + botuser + ", This command is restricted to admins only.")
# admin, able to ban
irc.send('PRIVMSG' + channel + ' :' + '.ban ' + argu)
then call this function in your while loop to handle all message you get
try:
commmanHandler(botuser, botmsg)
except Exception, e:
print e
irc.send('PRIVMSG' + channel + ' :' + e)
here would be my solution, and also, don't forget to give the bot moderator privilege.
So I have written a little bot that connects to twitch and is suppose to stay active till I close the script, but it seems after a elongated period of time the bot stops being connected to twitch and stops receiving anything. I think it is disconnecting, but I have no proof. Just the fact that it doesn't do anything after a while.
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server, port))
irc.send("PASS " + password + "\n")
irc.send("NICK " + name + "\n")
irc.send("JOIN " + channel + "\n")
def main():
while True:
data = irc.recv(1204)
data = data.strip('\r\n')
sendUsr = data.split(" ")
sendUsr = sendUsr[0]
sendUsr = sendUsr.split("!")
sendUsr = sendUsr[0]
sendUsr = sendUsr.strip(":")
print (data)
if data.find('PING') != -1 :
irc.send("PONG")
if data.find('PING') != -1 :
irc.send("PONG")
Needs to be changed to:
if data.find('PING')
irc.send("PONG :tmi.twitch.tv")
Try doing that & it should work.
I'm working on some Python code to automate github merge requests.
I found the following code below. When I run this, I get TypeError: string indices must be integers.
I've found several threads on here refrencing this error, but I'm not quit sure how to implement the fixes in the code.
#!/usr/bin/env python
import json
import requests
import datetime
OAUTH_KEY = "xxxxxxxxxxxx"
repos = ['my_app'] # Add all repo's you want to automerged here
ignore_branches = ['master', 'release', 'staging', 'development'] # Add 'master' here if you don't want to automerge into master
# Print merge/no-merge message to logfile
def print_message(merging):
if merging == True:
message = "Merging: "
else:
message = "Not merging: "
print message + str(pr_id) + " - " + user + " wants to merge " + head_ref + " into " + base_ref
# Merge the actual pull request
def merge_pr():
r = requests.put("https://api.github.com/repos/:owner/%s/pulls/%d/merge"%(repo,pr_id,),
data=json.dumps({"commit_message": "Auto_Merge"}),
auth=('token', OAUTH_KEY))
if "merged" in r.json() and r.json()["merged"]==True:
print "Merged: " + r.json()['sha']
else:
print "Failed: " + r.json()['message']
# Main
print datetime.datetime.now()
for repo in repos:
r = requests.get('https://api.github.com/repos/:owner/%s/pulls' % repo, auth=('token', OAUTH_KEY))
data = r.json()
for i in data:
head_ref=i["head"]["ref"]
base_ref=i["base"]["ref"]
user=i["user"]["login"]
pr_id = i["number"]
if base_ref in ignore_branches:
print_message(False)
else:
print_message(True)
merge_pr()
which line of code is showing a problem?
if it is this line:
'else:
message = "Not merging: "
print message + str(pr_id) + " - " + user + " wants to merge " + head_ref + " into " + base_ref'
then try putting this code right below
if merging == True:
message = "Merging: "
:
elif message == False:
message = "Not merging: "
print message + pr_id + " - " + user + " wants to merge " + head_ref + " into " + base_ref ''