Chatbot em Python
Publicado por Fernando (última atualização em 17/09/2015)
[ Hits: 12.477 ]
Homepage: https://github.com/phoemur/
Este script escrito em Python 3 faz login em um canal de IRC e fica aguardando. Ele responderá a mensagens privadas, simulando uma conversa, utilizando o protocolo do chatbot ALICE: http://alice.pandorabots.com/
O A.L.I.C.E (Artificial Linguistic Internet Computer Entity) é um chatterbot criado na Lehigh University por Richard S. Wallace, ativada em 1995, sendo um dos robôs mais populares da atualidade. É um projeto da internet que faz parte do Projeto Pandora. Este projeto envolve a criação de bots de todos os tipos, especialmente aqueles em bate-papo.
Este script em particular pega a resposta via HTTP e joga para o IRC e vice-versa. Edite o script para configurar o canal e o nickname desejados. Depois entre no canal com seu cliente favorito e converse com o robô (APENAS EM INGLÊS).
#!/usr/bin/env python3
import os
import re
import socket
import time
import urllib.request
import urllib.parse
import http.cookiejar
from random import randint
# SETTINGS
SERVER = 'irc.freenode.net'
PORT = 6667
CHANNEL = '##slackware'
NICK = 'chatbot_test'
class chatter(object):
def __init__(self):
self.url='http://sheepridge.pandorabots.com/pandora/talk?botid=b69b8d517e345aba&skin=custom_input'
self.cj = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))
self.opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201'),
('Accept', 'text/html, text/plain, text/css, text/sgml, */*;q=0.01'),
('Cache-Control', 'no-cache')]
def talk(self, m):
self.data = {'input': str(m)}
with self.opener.open(self.url, urllib.parse.urlencode(self.data).encode('UTF-8')) as url:
content = url.read().decode('UTF-8')
repl = re.search('<b>A.L.I.C.E.:</b> (.*)<br/>', content)
return str(repl.group(1))
def main():
# Create socket and log in
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER, PORT))
s.send('NICK {}\r\n'.format(NICK).encode('ISO-8859-1'))
s.send('USER {} {} {} .:\n'.format(NICK, NICK, NICK).encode('ISO-8859-1'))
s.send('JOIN {}\r\n'.format(CHANNEL).encode('ISO-8859-1'))
time.sleep(2)
print(s.recv(1024).decode('ISO-8859-1'))
# Mainloop
chatbot = chatter()
while True:
msg = s.recv(4096).decode('ISO-8859-1')
if len(msg) > 0:
print(msg)
if msg[0:4] == 'PING':
s.send(msg.replace('PING', 'PONG').encode('ISO-8859-1'))
if re.search('PRIVMSG {} :'.format(NICK), msg):
try:
subject = msg.split('!')[0].lstrip(':')
question = msg.split(':')[2].rstrip()
answer = chatbot.talk(question)
if re.search('[Jj]udge', answer):
answer = re.sub('[Jj]udge', subject, answer)
time.sleep(randint(3, 12))
s.send('PRIVMSG {} :{}\r\n'.format(subject, answer).encode('ISO-8859-1'))
except:
continue
if __name__ == '__main__':
main()
Preço do Dólar, Bitcoin e Euro em Python
Tradutor Inglês/Português utilizando MyMemory
Python script para inundação de email
Nenhum comentário foi encontrado.
Cirurgia para acelerar o openSUSE em HD externo via USB
Void Server como Domain Control
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
[Resolvido] VirtualBox can't enable the AMD-V extension
Como verificar a saúde dos discos no Linux
Como instalar , particionar, formatar e montar um HD adicional no Linux?
Como automatizar sua instalação do Ubuntu para desenvolvimento de software.
Não consigo instalar distro antiga no virtualbox nem direto no hd (14)
Quais os códigos mais dificeis que vcs sabem fazer? (12)
systemd-resol... precisa ser reiniciado periodicamente [RESOLVIDO] (7)









