Skip to content

Instantly share code, notes, and snippets.

@sebolio
Last active September 24, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebolio/564cf6b70409c7f6924d to your computer and use it in GitHub Desktop.
Save sebolio/564cf6b70409c7f6924d to your computer and use it in GitHub Desktop.
Módulo de Willie/Sopel para el bot de #Desarrolladores

Cambios

[25.09.2015] Añadida protección anti flood
[25.09.2015] Añadida protección anti líneas largas
[25.09.2015] Añadida protección anti DEOP
[25.09.2015] Añadida ayuda
[25.09.2015] Contador de números ahora tiene versión "light"

DesarrollaBot.py

from sopel.module import commands, event, rule, require_admin
from sopel import db
import json, urllib2, urllib, re, time, random, threading


cn="#desarrolladores"
def destino(f):
	def decor(bot, t):
		target = ' '.join(t.args[1].split( )[1:])
		return f(bot, t, target)
	return decor


#felicitar a una persona cuando cambia de nick de "des_XXX"
@event('NICK')
@rule('.*')
def uhnick(bot, t):
	nick = t.args[0]
	if not t.nick[0:4] == "des_": return

	time.sleep(2)
	felicitar = (
	"me gusta ese nick :D",
	"buena eleccion !",
	"esta super bueno",
	"es tu nombre real? te queda bien",
	"te queda bien !",
	"esta bueno ese nick",
	"excelente nick",
	"esta bien original!",
	"te queda mucho mejor",
	"te queda super bien",
	"buen nick !",
	"suena muy bien",
	"te queda perfecto",
	"ese es el nick ideal para ti !",
	"eso mismo estaba pensando",
	"buena, algo asi me imaginaba para ti",
	"asi te pescaran mucho mas !",
	)
	#bot.reply(felicitar[random.randint(0,len(felicitar)-1)], "notice")
	msg = "%s, %s" % (nick, felicitar[random.randint(0,len(felicitar)-1)])
	bot.msg("#sebl", "Notice a %s (ex %s): %s" % (nick, t.nick, msg))
	#bot.notice(msg, nick)
	bot.msg(cn, msg)


@commands('g','google')
@destino
def ggl(bot, t, args):
	IP = "200.27.2.2" #warevah
	res = json.load(urllib2.urlopen('https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s&userip=%s' % (urllib.quote_plus(args), IP)))
	try:
		primer = res['responseData']['results'][0]
		bot.reply('%s | %s' % (urllib.unquote(primer['url']), primer['titleNoFormatting']))
	except:
		bot.reply('no cacho')
		print str(res['results'])



@commands('sfull')
@destino
def c_spotfull(bot, t, arg):
	if arg == "1":
		bot.db.set_nick_value('tipoSong', 'full', "1")
		bot.reply('Ahora dire las canciones al usar .s')
	else:
		bot.db.set_nick_value('tipoSong', 'full', "0")
		bot.reply('Ahora el bot de KDDLB dira las canciones al usar .s')

	
@commands('contemos')
@destino
def contemos(bot, t, arg):
	try:
		arg = int(arg)
	except:
		bot.reply('cuentate este')
		return
	if not arg:
		bot.reply('hasta cuanto sabes contar?')
		return
	if not t.admin and int(arg) > 4:
		bot.reply('solo admins pueden contar hasta mas de 4, te quedaste en primaria.')
		return
	limite = 100
	arg = int(arg)
	if arg > limite:
		bot.reply("maximo %d wacho" % limite)
		return
	try:
		for i in range(arg):
			bot.reply(str(i+1))
		
	except:
		bot.reply("tay mal")


#comando que busca y arroja un link directo a una cancion en spotify
@commands('s', 'spotify')
@destino
def c_spotify(bot, t, arg):
	resp = json.load(urllib2.urlopen("http://ws.spotify.com/search/1/track.json?q=%s" % urllib.quote_plus(arg)))
	try:
		cancion = resp['tracks'][0]
		if bot.db.get_nick_value('tipoSong', 'full') == "1":
			bot.reply("Spotify: %s >> %s" % (cancion['name'], cancion['href']))
		else:
			bot.reply("Click para reproducir en Spotify >> %s. Para mas resultados: !spotify" % ( cancion['href']))
	except:
		bot.reply("Tuve problemas buscando %s. Me perdonas?" % arg)



#decorador que facilita uso de argumentos
@commands('greet', 'saludo')
@destino
def c_gre(bot, t, tar):
	saludo = ' '.join(t.args[1].split( )[1:])
	if saludo == "":
		bot.reply("Debes definir una frase: .greet <frase>")
		return
	if saludo == "off":
		bot.reply("saludo desactivado")
		bot.db.set_nick_value(t.nick, 'saludo', "None")
	else:
		bot.db.set_nick_value(t.nick, 'saludo', saludo)
		bot.reply('listo, te saludare cuando entres')

@commands('ayuda', 'comandos')
@destino
def ayuda(bot, t, comando):
	if comando: bot.reply('ayuda de %s en elaboracion' %comando)
	else:
		bot.reply('Comandos disponibles: google/g, spotify/s, traducir/tr, wiki/w, greet, regex, tiempo, estoyen, contemos')


@commands('web','c')
@destino
def wc(bot, t, nick):
        chan = t.args[0]
	if nick:
		bot.msg(chan, '%s: visita nuestro webchat en http://desarrolladores.chat' % nick)
	else:
		bot.msg(chan, 'Visita nuestro webchat en http://desarrolladores.chat')


@commands('src')
@destino
def c_src(bot, t, nick):
	bot.reply('Mi codigo fuente esta disponible en https://gist.github.com/sebcl/564cf6b70409c7f6924d')


@commands('hi')
@destino
def c_hi(bot, t, nick):
	if nick:
		bot.say('weeena %s!' % nick)
	else:
		bot.reply('wena!')


@commands('j')
@require_admin
def j(bot, trigger):
	bot.join(trigger.args[1].split( )[1])
	bot.reply('voy a '+trigger.args[1], 'notice')


@commands('p')
@require_admin
def p(bot, trigger):
	bot.part(trigger.args[1].split( )[1], 'a pedido de '+trigger.nick)
	bot.reply('salgo de '+trigger.args[1], 'notice')


@commands('raw')
@require_admin
def rr(bot, trigger):
	#bot.write(trigger.args[1][5:])
	args = trigger.args[1].split( )
	#bot.reply('ejecutando write con "%s", "%s"' % (args[1], ' '.join(args[2:])))
	bot.write((args[1], ' '.join(args[2:])))
	bot.notice('OK '+args[1] + (' '.join(args[2:])), trigger.nick)


@commands('r', 'regex')
def cmdr(bot, t):
	args = t.args[1].split( )
	bot.reply('buscando "%s"" "en "%s"' % (args[1], args[2:]))
	try:
		bot.reply('resultado: {}' % (re.search(args[1], args[2:]).groups()))
	except:
		bot.reply('sin coincidencias')


#ANTI DEOP
@event('MODE')
@rule('.*')
def nodeop(bot, t):
	i=t.args
	if '-o' in i[1] and 'mussa' in i[2:]:
		bot.write(('cs', 'op %s' % i[0]))
		bot.write(('cs', 'deop %s %s' % (i[0], t.nick)))


#PROTECCION ANTI FLOOD
canalFlood  = cn #"#desarrolladores"
tiemposFlood= {}
tiemposBans = {}
lineasFlood = 4
tiempoFlood = 5
tiempoBan   = 10
floodDebug  = False

letrasFlood = 300
letrasBan   = 5

def desbanear(bot, nick, chan):
	if floodDebug: bot.msg(canalFlood, 'desbaneando a %s' % nick)
	bot.write(('MODE', '%s -b %s' % (canalFlood, nick)))
	try:
		tiemposBans[nick].cancel()
		tiemposBans.pop(nick)
	except:
		return

def reiniciarMensajes(bot, nick, chan):
	tiemposFlood[nick].cancel()
	tiemposFlood.pop(nick)
	mensajes = bot.db.get_nick_value(nick, 'flood'+chan)
	if floodDebug: bot.msg(canalFlood, 'reiniciando mensajes para %s (%s)' % (nick, mensajes))
	bot.db.set_nick_value(nick, 'flood'+chan, 0)
	

@event('PRIVMSG')
@rule('.*')
def fl_prev(bot, t):
        chan = t.args[0]
	if not chan == canalFlood: return
	if t.nick in ('Granota', 'onSeb', 'sebcl', 'sdelv'): return

	#ban por letras
	largo = len(' '.join(t.args[1:]))
	if largo >= letrasFlood:
		threading.Timer(letrasBan, desbanear, [bot, t.nick, chan]).start()
		bot.write(('MODE', '%s +b %s' % (canalFlood, t.nick)))
		bot.reply("lineas tan largas (%s letras) molestan y dificultan la lectura, calmate %ss." % (largo, letrasBan))
		return		


	susMensajes = bot.db.get_nick_value(t.nick, 'flood'+chan)
	if susMensajes == None: susMensajes=0
	susMensajes = int(susMensajes) + 1
	bot.db.set_nick_value(t.nick, 'flood'+chan, susMensajes)

	if susMensajes >= lineasFlood:
		tiemposBans[t.nick] = threading.Timer(tiempoBan, desbanear, [bot, t.nick, chan])
		tiemposBans[t.nick].start()
		bot.write(('MODE', '%s +b %s' % (canalFlood, t.nick)))
		bot.reply('has sido silenciado %s segundos por flood, calmate.' % tiempoBan)
	        bot.db.set_nick_value(t.nick, 'flood'+chan, 0)
		return
	else:
		if floodDebug: bot.msg(canalFlood, 'previniendo flood, mensajes de %s(%s) en 5 segundos: %s/%s' % (t.nick, chan, susMensajes, lineasFlood))


	if t.nick in tiemposFlood: #cada vez que hable se reinician los segundos de reseteo
        	tiemposFlood[t.nick].cancel()
	        tiemposFlood.pop(t.nick)
		
	tiemposFlood[t.nick] = threading.Timer(tiempoFlood, reiniciarMensajes, [bot, t.nick, chan])
	tiemposFlood[t.nick].start()


#SALUDOS A LOS RECIEN LLEGADOS (soporte de .greet)
@event('JOIN')
@rule('.*')
def eeljoin(bot, t):
	chan = t.args[0]
	if bot.nick == t.nick:
		return
	if chan.lower() == "#chile":
		bot.msg(chan, "Hola, "+t.nick+". Este canal no esta habilitado, te recomendamos ##chile y #desarrolladores")
		return
	saludo = bot.db.get_nick_value(t.nick, 'saludo')

	if not saludo == "None" and not saludo == None:
		bot.msg(chan, "[%s] %s" % (t.nick, saludo))

	else:

		time.sleep(3)
		if t.nick[0:4] == "des_":
			msg = "hola %s .. considera ponerte un nick original :)" %t.nick
			bot.msg("#sebl", "Notice a %s: %s" % (t.nick, msg))
			#bot.notice(msg, t.nick)
			bot.msg(cn, msg)

		else:
			saludos = (
			"hola %s, como andas",
			"bienvenido %s",
			"hola %s",
			"%s: buenas",
			"buenas %s",
			"wena %s",
			"hey %s como te trata la vida?",
			"bienvenido al canal,  %s",
			"hola %s! eres programador?",
			"hey %s como andas",
			"%s: hola! eres programador",
			"hola %s! de donde eres?",
			"hey %s como andas",
			"que tal %s",
			"hey %s de donde eres",
			"hola %s",
			"hey %s",
			"como andas %s?",
			"hola de donde eres %s?",
			)
			msg = saludos[random.randint(0,len(saludos)-1)] % t.nick
			bot.msg("#sebl", "Notice a %s: %s" % (t.nick, msg))
			#bot.notice(msg, t.nick)
			bot.msg(cn, msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment