-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.py
executable file
·166 lines (127 loc) · 4.61 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
An IRC bot that answers random questions, keeps a log from the IRC-chat,
easy to integrate in a webpage and montores a phpBB forum for latest topics
by loggin in to the forum and checking the RSS-feed.
You need to install additional modules.
# Install needed modules in local directory
pip3 install --target modules/ feedparser beautifulsoup4 chardet
Modules in modules/ will be loaded automatically. If you want to use a
different directory you can start the program like this instead:
PYTHONPATH=modules python3 main.py
# To get help
PYTHONPATH=modules python3 main.py --help
# Example of using options
--server=irc.bsnet.se --channel=#db-o-webb
--server=irc.bsnet.se --port=6667 --channel=#db-o-webb
--nick=marvin --ident=secret
# Configuration
Check out the file 'marvin_config_default.json' on how to configure, instead
of using cli-options. The default configfile is 'marvin_config.json' but you
can change that using cli-options.
# Make own actions
Check the file 'marvin_strings.json' for the file where most of the strings
are defined and check out 'marvin_actions.py' to see how to write your own
actions. Its just a small function.
# Read from incoming
Marvin reads messages from the incoming/ directory, if it exists, and writes
it out the the irc channel.
"""
import argparse
import json
import logging
import logging.config
import os
import sys
from discord_bot import DiscordBot
from irc_bot import IrcBot
import marvin_actions
import marvin_general_actions
#
# General stuff about this program
#
PROGRAM = "marvin"
AUTHOR = "Mikael Roos"
EMAIL = "[email protected]"
VERSION = "0.3.0"
MSG_VERSION = "{program} version {version}.".format(program=PROGRAM, version=VERSION)
LOG = logging.getLogger("main")
def printVersion():
"""
Print version information and exit.
"""
print(MSG_VERSION)
sys.exit(0)
def mergeOptionsWithConfigFile(options, configFile):
"""
Read information from config file.
"""
if os.path.isfile(configFile):
with open(configFile, encoding="UTF-8") as f:
data = json.load(f)
options.update(data)
res = json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))
LOG.info("Read configuration from config file '%s'.", configFile)
LOG.info("Current configuration is: %s", res)
else:
LOG.info("Config file '{%s}' is not readable, skipping.", configFile)
return options
def parseOptions(options):
"""
Merge default options with incoming options and arguments and return them as a dictionary.
"""
parser = argparse.ArgumentParser()
parser.add_argument("protocol", choices=["irc", "discord"], nargs="?", default="irc")
parser.add_argument("-v", "--version", action="store_true")
parser.add_argument("--config")
for key, value in options.items():
parser.add_argument(f"--{key}", type=type(value))
args = vars(parser.parse_args())
if args["version"]:
printVersion()
if args["config"]:
mergeOptionsWithConfigFile(options, args["config"])
for parameter in options:
if args[parameter]:
options[parameter] = args[parameter]
res = json.dumps(options, sort_keys=True, indent=4, separators=(',', ': '))
LOG.info("Configuration updated after cli options: %s", res)
return options
def determineProtocol():
"""Parse the argument to determine what protocol to use"""
parser = argparse.ArgumentParser()
parser.add_argument("protocol", choices=["irc", "discord"], nargs="?", default="irc")
arg, _ = parser.parse_known_args()
return arg.protocol
def createBot(protocol):
"""Return an instance of a bot with the requested implementation"""
if protocol == "irc":
return IrcBot()
if protocol == "discord":
return DiscordBot()
raise ValueError(f"Unsupported protocol: {protocol}")
def setupLogging():
"""Set up the logging config"""
with open("logging.json", encoding="UTF-8") as f:
config = json.load(f)
logging.config.dictConfig(config)
def main():
"""
Main function to carry out the work.
"""
setupLogging()
protocol = determineProtocol()
bot = createBot(protocol)
options = bot.getConfig()
options.update(mergeOptionsWithConfigFile(options, "marvin_config.json"))
config = parseOptions(options)
bot.setConfig(config)
actions = marvin_actions.getAllActions()
general_actions = marvin_general_actions.getAllGeneralActions()
bot.registerActions(actions)
bot.registerGeneralActions(general_actions)
bot.begin()
sys.exit(0)
if __name__ == "__main__":
main()