Skip to content

Commit

Permalink
Merge pull request #54 from clojureverse/rtmbot-python3
Browse files Browse the repository at this point in the history
Port rtmbot to python3 and v2 of the slackclient
  • Loading branch information
plexus committed Jul 15, 2019
2 parents 9340db1 + 4cc22fd commit f62882c
Showing 1 changed file with 99 additions and 61 deletions.
160 changes: 99 additions & 61 deletions bin/rtmbot.py
Original file line number Diff line number Diff line change
@@ -1,92 +1,130 @@
#!/usr/bin/env python
#!/usr/bin/env python3

# Script that logs slack messages to text files. Configure with a "rtmbot.conf"
# text file like this
#
# SLACK_TOKEN: "xox-...."
# LOGFILE: /var/log/slackbot.log
# DAEMON: True
#
# Will create files like logs/2018-03-10.txt, containing one JSON object per
# line, for each event. Will log all events received from the Slack RTM API
# except for "pong", "hello", and "user_typing".
# line, for each event. Will log all events in the channels except for
# "hello", "pong", and "user_typing".

import sys
sys.dont_write_bytecode = True

import glob
import yaml
import json
import os
import sys
import time
import logging

from datetime import date
from json import dumps
import datetime
import codecs

from slackclient import SlackClient
import functools

def process_message(data):
with codecs.open(date.today().strftime('logs/%Y-%m-%d.txt'), 'ab', 'utf-8') as f:
# print(dumps(data))
f.write(dumps(data))
f.write("\n")
import slack

rtm_event_list = [
'accounts_changed',
'bot_added',
'bot_changed',
'channel_archive',
'channel_created',
'channel_deleted',
'channel_history_changed',
'channel_joined',
'channel_left',
'channel_marked',
'channel_rename',
'channel_unarchive',
'commands_changed',
'dnd_updated',
'dnd_updated_user',
'email_domain_changed',
'emoji_changed',
'external_org_migration_finished',
'external_org_migration_started',
'file_change',
'file_comment_added',
'file_comment_deleted',
'file_comment_edited',
'file_created',
'file_deleted',
'file_public',
'file_shared',
'file_unshared',
'goodbye',
'group_archive',
'group_close',
'group_deleted',
'group_history_changed',
'group_joined',
'group_left',
'group_marked',
'group_open',
'group_rename',
'group_unarchive',
# 'hello',
'im_close',
'im_created',
'im_history_changed',
'im_marked',
'im_open',
'manual_presence_change',
'member_joined_channel',
'member_left_channel',
'message',
'pin_added',
'pin_removed',
'pref_change',
'presence_change',
'presence_query',
'presence_sub',
'reaction_added',
'reaction_removed',
'reconnect_url',
'star_added',
'star_removed',
'subteam_created',
'subteam_members_changed',
'subteam_self_added',
'subteam_self_removed',
'subteam_updated',
'team_domain_change',
'team_join',
'team_migration_started',
'team_plan_change',
'team_pref_change',
'team_profile_change',
'team_profile_delete',
'team_profile_reorder',
'team_rename',
'user_change',
# 'user_typing',
]

class RtmBot(object):
def __init__(self, token):
self.last_ping = 0
self.token = token
self.slack_client = None
def connect(self):
"""Convenience method that creates Server instance"""
self.slack_client = SlackClient(self.token)
self.slack_client.rtm_connect()
def start(self):
self.connect()
while True:
for reply in self.slack_client.rtm_read():
self.input(reply)
self.autoping()
time.sleep(.1)
def autoping(self):
#hardcode the interval to 3 seconds
now = int(time.time())
if now > self.last_ping + 3:
self.slack_client.server.ping()
self.last_ping = now
def input(self, data):
if "type" in data and not data["type"] in {"pong", "user_typing", "hello"}:
process_message(data)
def process_event(event_type, **payload):
data = payload['data']
data['type'] = event_type
with codecs.open(datetime.date.today().strftime('logs/%Y-%m-%d.txt'), 'ab', 'utf-8') as f:
f.write(json.dumps(data))
f.write("\n")

def main_loop():
if "LOGFILE" in config:
logging.basicConfig(filename=config["LOGFILE"], level=logging.INFO, format='%(asctime)s %(message)s')
logging.info(directory)
logging.info('rtmbot started.')
try:
bot.start()
rtm_client.start()
except KeyboardInterrupt:
sys.exit(0)
except:
logging.exception('OOPS')
logging.exception('Caught rtmbot exception.')

if __name__ == "__main__":
directory = os.path.dirname(sys.argv[0])
if not directory.startswith('/'):
directory = os.path.abspath("{}/{}".format(os.getcwd(),
directory
))

config = yaml.load(file('rtmbot.conf', 'r'))
bot = RtmBot(config["SLACK_TOKEN"])
site_plugins = []
files_currently_downloading = []
job_hash = {}

if config.has_key("DAEMON"):
if config["DAEMON"]:
import daemon
with daemon.DaemonContext():
main_loop()
config = yaml.load(open('rtmbot.conf', 'r'))
slack_token = config["SLACK_TOKEN"]
rtm_client = slack.RTMClient(token=slack_token)
for e in rtm_event_list:
slack.RTMClient.on(event=e, callback=functools.partial(process_event, e))
main_loop()

0 comments on commit f62882c

Please sign in to comment.