Skip to content

Instantly share code, notes, and snippets.

@davidbegin
Last active June 28, 2020 23:00
Show Gist options
  • Save davidbegin/6a94447af65e95483fc9df08f4e97942 to your computer and use it in GitHub Desktop.
Save davidbegin/6a94447af65e95483fc9df08f4e97942 to your computer and use it in GitHub Desktop.
Simplest message to IRC bot
import socket
import os
channel = os.environ["CHANNEL"]
def _handshake(server):
# Get the value for this here: https://twitchapps.com/tmi/
token = os.environ["TWITCH_OAUTH_TOKEN"]
# Note the bot name will not be what is specifed here,
# unless the Oauth token was generated for a Twitch Account with the same Name
bot = os.environ["BOT_NAME"]
print(f"Connecting to #{channel} as {bot}")
print(server.send(bytes("PASS " + token + "\r\n", "utf-8")))
print(server.send(bytes("NICK " + bot + "\r\n", "utf-8")))
print(server.send(bytes("JOIN " + f"#{channel}" + "\r\n", "utf-8")))
def _connect_to_twitch():
connection_data = ("irc.chat.twitch.tv", 6667)
server = socket.socket()
server.connect(connection_data)
_handshake(server)
return server
def send_message(server, msg):
server.send(
bytes("PRIVMSG " + f"#{channel}" + " :" + msg + "\n", "utf-8")
)
def _is_command_msg(msg):
return msg[0] == "!" and msg[1] != "!"
def process_msg(irc_response):
user, msg = _parse_user_and_msg(irc_response)
if _is_command_msg(msg):
print(f"We want to run command {msg}")
else:
print(f"{user}: {msg}")
# TODO: refactor this sillyness
def _parse_user_and_msg(irc_response):
user_info, _, _, *raw_msg = irc_response
raw_first_word, *raw_rest_of_the_message = raw_msg
first_word = raw_first_word[1:]
rest_of_the_message = " ".join(raw_rest_of_the_message)
user = user_info.split("!")[0][1:]
msg = f"{first_word} {rest_of_the_message}"
return user, msg
def run_bot(server):
while True:
irc_response = server.recv(2048).decode("utf-8").split()
print(irc_response)
if irc_response[1] == "PRIVMSG":
process_msg(irc_response)
server = _connect_to_twitch()
send_message(server, "Hello")
run_bot(server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment