Skip to content

Commit 8fe6324

Browse files
author
Braxton McLean
authored
Merge pull request #3 from braxton-mclean/config
Added Admin functionality, and addressed non-ascii character errors
2 parents 31842cb + 9a12aac commit 8fe6324

File tree

6 files changed

+55
-14
lines changed

6 files changed

+55
-14
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/logs/*
22
/secrets/*
3+
/config/*
34
*.pyc
45
# swap
56
[._]*.s[a-v][a-z]

README.md

+1-4
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,7 @@ As well as messaging them a custom message upon joining the Slack team.
3535

3636
# Installing Dependencies
3737
PantherBot requires several python libraries to function. These can be easily installed with the `setup.bat` or `setup.sh` file.
38-
```
39-
sudo setup.sh
40-
```
41-
`setup.sh` should be run with elevated privileges to ensure dependencies install correctly (this is an issue for most unless you're using a virtualenv).
38+
`setup.sh` should be run with elevated privileges to ensure dependencies install correctly (this is an issue for most unless you're using a virtualenv) (`sudo sh setup.sh` should be good enough).
4239
Likewise, pip may request your permission or a prompt if using the `setup.bat` file. If it fails, try using administrative privileges.
4340

4441
# Setting up PantherBot

bot.py

+49-9
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,20 @@
99
from apiclient.discovery import build
1010
#Other imports
1111
from scripts import Help, CatFacts, Flip, GiveFortune, Coin, Pugbomb, Unflip, Calendar, TaskMe
12-
import os, sys, codecs, websocket, datetime, json, logging
12+
import os, io, sys, codecs, websocket, datetime, json, logging
1313

1414
#Custom Variables
1515
BOT_NAME = 'PantherBot' #Set to whatever you would like the Bot to post his name as in Slack
1616
BOT_ICON_URL = 'http://i.imgur.com/QKaLCX7.png' #Set to change whatever the profile picture is when the Bot posts a message
1717
SLACK = True #Set to False to disable connecting to the Slack RTM API... for whatever reason
1818
GOOGLECAL = False #Set to False to disable connecting and enabling the Google Calendar API integration
19-
LOGGER = False #Set to True to get "detailed" error messages in the console. These error messages can vary from very helpful to utterly useless
19+
LOGGER = True #Set to True to get "detailed" error messages in the console. These error messages can vary from very helpful to utterly useless
2020
GOOGLECALSECRET = "PantherBot-test.json" #Can make this a system environment variable if you really want to be careful
2121
NEWUSERGREETING = True #Set to True to send users that join the Slack Team a message (GREETING), appended with a link (LINK) (used for whatever you want, in our case, a "How to Use Slack" document)
2222
LINK = "https://test.link.pantherhackers.com" #link to be appended to GREETING
2323
GREETING = "Greetings newcomer! This is your friendly neighborhood PantherBot, a bot created by your fellow members of PantherHackers! We just wanted to say hello, and welcome you to the family! If Slack seems intimidating, have no fear! If you've ever messed with the likes of Discord, it is a lot like that. If you haven't messed with that either, again, no worries.\nTo get started, you have your default channels on the left (expand the menu by tapping the Panther icon in the top left if you are on mobile). To join more channels, click/tap on the plus button next to \"CHANNELS\" and you'll be well on your way.\nIf you are interested to learn more about Slack, you can go to our custom tutorial here: " + LINK
24-
ADMIN = ["U25PPE8HH", "U262D4BT6", "U0LAMSXUM", "U3EAHHF40"] #Contains user IDs for those allowed to run $ commands
24+
USER_LIST = []
25+
ADMIN = [] #["U25PPE8HH", "U262D4BT6", "U0LAMSXUM", "U3EAHHF40"] Contains user IDs for those allowed to run $ commands
2526

2627
#initialize basic logging to see errors more easily
2728
if LOGGER == True:
@@ -41,10 +42,7 @@
4142

4243
#function that is called whenever there is an event, including status changes, join messages, typing status, emoji reactions, everything
4344
def on_message(ws, message):
44-
#converts to usable string format
45-
s = message.encode('ascii')
46-
47-
#converts to JSON so we can parse through it easier
45+
s = message
4846
response = json.loads(s)
4947
print "PantherBot:LOG:message:" + response["type"]
5048

@@ -73,9 +71,9 @@ def on_message(ws, message):
7371
script_dir = os.path.dirname(__file__)
7472
fullDir = os.path.join(script_dir, filename)
7573
if os.path.isfile(fullDir) == True:
76-
target = open(fullDir, "a")
74+
target = io.open(fullDir, "a", encoding='utf-8')
7775
else:
78-
target = open(fullDir, "w+")
76+
target = io.open(fullDir, "w+",encoding='utf-8')
7977
user_name = temp_user["user"]["profile"]["first_name"] + " " + temp_user["user"]["profile"]["last_name"]
8078

8179
#format:
@@ -87,6 +85,7 @@ def on_message(ws, message):
8785
target.close()
8886

8987
#Riyan's denial
88+
#GIVES THE 'user' error we always see, its cause bots dont have the user field and its like hold up
9089
if "U0LJJ7413" in response["user"]:
9190
if response["text"][:1] in ["!", "$"] or response["text"].lower() in ["hey pantherbot", "pantherbot ping"]:
9291
rMsg(response, "No.")
@@ -150,6 +149,11 @@ def on_message(ws, message):
150149
return
151150
else:
152151
rMsg(response, "It seems you aren't authorized to enable logging. If you believe this a mistake, contact the maintainer(s) of PantherBot")
152+
if args[0].lower() == "$admin":
153+
if response["user"] in ADMIN:
154+
print "PantherBot:LOG:Approved User called $admin"
155+
if args[1].lower() == "add":
156+
adminAdd(response, args)
153157

154158
#If not an ! or $, checks if it should respond to another message format, like a greeting
155159
elif response["text"].lower() == "hey pantherbot":
@@ -176,6 +180,9 @@ def on_message(ws, message):
176180
username=BOT_NAME,
177181
icon_url=BOT_ICON_URL
178182
)
183+
USER_LIST = sc.api_call(
184+
"users.list",
185+
)
179186

180187
#!/usr/bin/env python
181188
# -*- coding: utf-8 -*-
@@ -228,6 +235,27 @@ def log(response, words):
228235
LOGC = DUMMY
229236
return
230237

238+
#Command for adding members to the admin list based on username.
239+
def adminAdd(response, words):
240+
print "PantherBot:LOG:admin add called"
241+
filename = "config/admin.txt"
242+
#this is the only reason this function is here
243+
script_dir = os.path.dirname(__file__)
244+
fullDir = os.path.join(script_dir, filename)
245+
246+
if os.path.isfile(fullDir) == True:
247+
target = open(fullDir, "a")
248+
else:
249+
target = open(fullDir, "w+")
250+
for user in USER_LIST["members"]:
251+
for x in range(2, len(words)):
252+
if user["name"] == words[x]:
253+
ADMIN.append(user["id"])
254+
#format:
255+
#USERID\n
256+
target.write(user["id"] + "\n")
257+
target.close()
258+
231259
#Unused things for WebSocketApp
232260
def on_error(ws, error):
233261
print error
@@ -281,6 +309,13 @@ def rMsg(response, t):
281309

282310
#If for some reason you need to debug without connecting to the Slack RTM API... this is for you.
283311
if SLACK == True:
312+
#load config files
313+
filename = "config/admin.txt"
314+
script_dir = os.path.dirname(__file__)
315+
fullDir = os.path.join(script_dir, filename)
316+
ADMIN = [line.rstrip('\n') for line in open(fullDir)]
317+
print ADMIN
318+
284319
#Get Token from local system environment variables
285320
t = os.environ['SLACK_API_TOKEN']
286321
#initiates the SlackClient connection
@@ -293,6 +328,11 @@ def rMsg(response, t):
293328
token = t
294329
)
295330

331+
#Update current USER_LIST (since members may join while PantherBot is off, I think its safe to make an API call every initial run)
332+
USER_LIST = sc.api_call(
333+
"users.list"
334+
)
335+
296336
#creates WebSocketApp based on the wss returned by the RTM API
297337
print "PantherBot:LOG:Starting WebSocketApplication and connection"
298338
ws = websocket.WebSocketApp(bot_conn["url"],

setup.bat

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
pip install -r requirements.txt
22
mkdir logs
33
mkdir secrets
4+
mkdir cocnfig

setup.sh

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
pip install -r requirements.txt
33
mkdir logs
44
mkdir secrets
5+
mkdir config

start.sh

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
#!/bin/bash
2-
python bot.py
2+
#this is no longer a relative path but for our sake of keeping the Pi as clean as possible, this is necessary.
3+
python ~/PantherBot/bot.py

0 commit comments

Comments
 (0)