Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
*.ini
*.pyc
botmily.db
botmily.7z
Thumbs.db
tells.csv
quotedb.7z
quote.csv
botmily.sql
quote table.csv
Thumbs.db
quotej.csv
Thumbs.db
temp.jpg
Thumbs.db
Binary file added Thumbs.db
Binary file not shown.
98 changes: 89 additions & 9 deletions botmily/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,24 @@
import socket
import sys
import traceback

import math
from botmily import config
from botmily import irc
import plugins

import select
import time

class bot():
def __init__(self):
self.server = config.server
self.nickname = config.name
self.realname = b"Botmily https://github.com/kgc/botmily"
self.realname = b"Botdrew https://github.com/kgc/botmily"
self.channels = config.channels
self.password = config.password

self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.server, 6667))
self.irc = irc.irc_handler(self.socket, self , self.irc_error)
self.sa_user = config.sa_user
self.sa_password = config.sa_password
self.timeout = config.timeout

print("Initializing plugins...")
self.commands = {}
Expand All @@ -34,7 +36,56 @@ def __init__(self):
self.commands.update(plugin.commands)
self.triggers.extend(plugin.triggers)

asyncore.loop()

Continue_State = True
print("Attempting Connection! Mash Ctrl+C or whatever to exit.")
while (Continue_State):
Continue_State = self.connect()
if Continue_State:
try:
print("Sleeping for 30 seconds before retrying...")
time.sleep(30)
except KeyboardInterrupt, err:
Continue_State = False

print("Exiting!")

def drop(self, calling_irc_handler):
# Prevent accidental rogue irc timers?
print("DC message from " + calling_irc_handler.__str__())
if self.irc is calling_irc_handler:
self.socket.close()
asyncore.close_all()
else:
print("Bot is ignoring out of date handler. Masti is bad at threading!")

def connect(self):
# we COULD close our old socket, if we have one, but... it should get closed in garbage collection so who cares?

print("Connecting to:",self.server)

self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
self.socket.connect((self.server, 6667))
except socket.gaierror, err:
print("Could not initiate connection!")
return True

self.irc = irc.irc_handler(self.socket, self , self.irc_error)

print("Connection loop starting...")

try:
asyncore.loop()
except select.error, err:
pass
except KeyboardInterrupt, err:
print(" <- Keyboard Interupt detected, cancelling thread timers where possible...")
self.irc.stop()
return False

return True

def join(self, nick, user, host, channel):
if nick == self.nickname:
Expand All @@ -60,8 +111,20 @@ def privmsg(self, nick, user, host, channel, message):
if len(possible_commands) == 1:
message_data["command"] = possible_commands[0][0]
try:
# Contact the bound function, supplying message data and self as a paramter
output = possible_commands[0][1](message_data, self)
self.say(nick, channel, output)
if isinstance(output, str) or isinstance(output, unicode):
self.say(nick, channel, output)
elif isinstance(output, dict):
# Merge the two dictionaries:
o_dict = message_data.copy()
o_dict.update(output)
# Check we have the new output key
if "output" in o_dict:
self.say(o_dict["nick"], o_dict["channel"], o_dict["output"])
else:
# Fuck it, print it anyway:
self.say(nick, channel, output)
except Exception, E:
print('Encountered error while processing commmand %s with input %s' %(str(possible_commands[0][1]),str(message_data)))
traceback.print_exc()
Expand All @@ -85,9 +148,26 @@ def privmsg(self, nick, user, host, channel, message):
print('Encountered error while processing trigger %s with input %s' %(str(function),str(message_data)))
traceback.print_exc()
self.say(nick,channel,'I crashed while trying to deal with something you said @_@')

#for omni in self.allmsg:


def say(self, nick, channel, output):
maxsay = 400
if output is None:
return
if len(output) > maxsay:
maxval = int(math.ceil(len(output)/float(maxsay)))
for x in range(0,maxval):
if x < 2:
self.do_msg(nick,channel,output[maxsay*x:maxsay*(x+1)])
else:
self.do_msg(nick,channel,output[maxsay*x:maxsay*(x+1) - 100] + "... %d lines additional ommitted!" % (maxval - 3))
break
else:
self.do_msg(nick,channel,output)

def do_msg(self,nick,channel,output):
if output is None:
return
if self.nickname == channel:
Expand All @@ -97,4 +177,4 @@ def say(self, nick, channel, output):

def irc_error(self):
print('Nasty error caught, trying to continue anyway , details below : ')
traceback.print_exc()
traceback.print_exc()
75 changes: 40 additions & 35 deletions botmily/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
server = ''
channels = []
password = ''
sa_user = ''
sa_password = ''
timeout = 300
tumblr_blog = ''
tumblr_user = ''
tumblr_password = ''
Expand All @@ -17,38 +20,40 @@
lastfm_api_key = ''

def getConfig():
global name
global server
global channels
global password
global tumblr_blog
global tumblr_user
global tumblr_password
global tumblr_title
global tumblr_tumbling
global wolframalpha_api_key
global lastfm_api_key
global oauth_token
global oauth_secret
global consumer_key
global consumer_secret
config = ConfigParser()
config.read('config.ini')
name = config.get('main', 'name')
server = config.get('main', 'server')
channels = config.get('main', 'channels').split(" ")
password = config.get('main', 'password')
tumblr_tumbling = config.getboolean('tumblr','tumbling')
tumblr_blog = config.get('tumblr', 'blog')
tumblr_user = config.get('tumblr' , 'user')
tumblr_password = config.get('tumblr', 'password')
tumblr_title = config.get('tumblr','post_titles')
wolframalpha_api_key = config.get('wolframalpha', 'api_key')
lastfm_api_key = config.get('lastfm', 'api_key')
oauth_token = config.get('twitter', 'oauth_token')
oauth_secret = config.get('twitter', 'oauth_secret')
consumer_key = config.get('twitter', 'consumer_key')
consumer_secret = config.get('twitter', 'consumer_secret')
print("I will use the name: " + name)
print("I will connect to the server: " + server)
print("I will connect to the channels: " + ", ".join(channels))
global name
global server
global channels
global password
global sa_user
global sa_password
global timeout
global wolframalpha_api_key
global lastfm_api_key
global oauth_token
global oauth_secret
global consumer_key
global consumer_secret
global YOUTUBE_API_KEY
config = ConfigParser()
config.read('config.ini')
name = config.get('main', 'name')
server = config.get('main', 'server')
channels = config.get('main', 'channels').split(" ")
password = config.get('main', 'password')
sa_user = config.get('main', 'sa_user')
sa_password = config.get('main', 'sa_password')
try:
timeout = int(config.get('main', 'timeout'))
except:
print("Could not convert timeout value to integer! Defaulting to 300!")
timeout = 300
wolframalpha_api_key = config.get('wolframalpha', 'api_key')
lastfm_api_key = config.get('lastfm', 'api_key')
oauth_token = config.get('twitter', 'oauth_token')
oauth_secret = config.get('twitter', 'oauth_secret')
consumer_key = config.get('twitter', 'consumer_key')
consumer_secret = config.get('twitter', 'consumer_secret')
YOUTUBE_API_KEY = config.get('youtube', 'api_key')
print("I will use the name: " + name)
print("I will connect to the server: " + server)
print("I will connect to the channels: " + ", ".join(channels))
34 changes: 32 additions & 2 deletions botmily/irc.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from __future__ import division
from __future__ import print_function
#from __future__ import print_function
from __future__ import unicode_literals

import asynchat
import time
import unicodedata

from threading import Timer

controls = {'bold': '\u0002',
'color': '\u0003',
'clear': '\u000f'}
Expand Down Expand Up @@ -52,10 +54,15 @@ def __init__(self, sock, bot , error_callback = None):
self.set_terminator(b"\r\n")
self.bot = bot
self.push(b"NICK %s\r\n" %bot.nickname)
self.push(b"USER botmily 0 0 :Botmily\r\n")
self.push(b"USER botdrew 0 0 :Botdrew\r\n")
if error_callback:
self.handle_error = error_callback

# Set up a ping counter:
self.pingcount = 0
self.mytimer = Timer(self.bot.timeout, self.ping_check, ())
self.mytimer.start()

def collect_incoming_data(self, data):
self.ibuffer += data

Expand Down Expand Up @@ -105,15 +112,38 @@ def pong(self, message):
self.push(b"PONG " + message + b"\r\n")

def raw_PRIVMSG(self, prefix, params):
# Increment the number of messages seen here as well because maybe that will be more robust:
self.pingcount += 1

nick, user, host = split_prefix(prefix)
channel = params[0]
message = params[-1].decode("utf-8", "replace")
self.bot.privmsg(nick, user, host, channel, message)

def raw_PING(self, prefix, params):
#print("Ping")
self.pingcount += 1
self.pong(params[0])

def raw_JOIN(self, prefix, params):
nick, user, host = split_prefix(prefix)
channel = params[0]
self.bot.join(nick, user, host, channel)

def ping_check(self):
print self.__str__() + " ~ Seen Pings/Messages:",self.pingcount
self.mytimer.cancel()
if self.pingcount > 0:
self.mytimer = Timer(self.bot.timeout, self.ping_check, ())
self.mytimer.start()
self.pingcount = 0
else:
print self.__str__() + " ~ Suspected Disconnection? Closing socket."
asynchat.async_chat.handle_close(self)
self.bot.drop(self)
return False

def stop(self):
if self.mytimer:
self.mytimer.cancel()
return 0
69 changes: 0 additions & 69 deletions faceSquares.py

This file was deleted.

Loading