This repository has been archived by the owner on Oct 22, 2018. It is now read-only.
/
dinofactsbot.py
executable file
·103 lines (67 loc) · 3.08 KB
/
dinofactsbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python
import os
import logging
import praw
import requests
from restclient import RestClient
from time import sleep
from ConfigParser import SafeConfigParser
from logging.handlers import TimedRotatingFileHandler
def respondWithFact(fact, comment):
comment.reply(fact)
def botInfo(comment):
reply = """Hi, i'm DinoFactsBot. I reply to certain comments with useless facts about Dinosaurs!\n\n
USAGE: Call me by mentioning my username +fact. E.g. /u/phalosaurus_ +fact\n\n
My code can be found here: https://github.com/chelnak/Botosaur"""
comment.reply(reply)
def main():
#Do requests SSL stuff
#requests.packages.urllib3.disable_warnings()
#Get configuration
parser = SafeConfigParser()
parser.read('/etc/dinofactsbot/config.ini')
config = parser._sections['defaults']
#Configure logging
logger = logging.getLogger('DINOFACTSBOT')
logger.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(config['log_file'],when='midnight')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
#Initialize rest client
client = RestClient(config['api_host'])
#Initialize reddit client
logger.info('Initializing reddit API client')
r = praw.Reddit(user_agent = config['user_agent'])
#login
logger.info('Attempting to log in to reddit with credentials from config.ini')
r.login(config['bot_user'], config['bot_pass'])
#Get reddit user
logger.info('Retrieving subreddit: ' + config['subreddit'])
subreddit = r.get_subreddit(config['subreddit'])
#Main loop of program
logger.info('Beginning monitor..')
logger.info('Retrieving comments with limit of ' + str(config['limit']))
while True:
try:
comments = subreddit.get_comments(limit=int(config['limit']))
for comment in comments:
if client.isCommentProcessed(comment.id) is 0:
logger.info('Processing ' + comment.id + ' by user ' + comment.author.name)
record = client.insertRecord(comment)
logger.info('New log record created: ' + str(record['id']))
if (config['trigger'] in comment.body):
logger.info('Found trigger in ' + comment.id)
fact = client.getRandom()
logger.info('Retrieved fact:{fact} '.format(fact=fact['id']))
comment.reply(fact['fact'])
logger.info('Updating record field')
client.updateRecord(record['id'], fact['id'])
else:
logger.info('No trigger found. Ignorinng comment')
sleep(int(config['poll_time']))
except Exception as e:
logger.error(e)
if __name__ == "__main__":
main()