aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas "Cakeisalie5" Touhey <thomas@touhey.fr>2017-08-05 12:00:09 +0200
committerThomas "Cakeisalie5" Touhey <thomas@touhey.fr>2017-08-05 12:00:09 +0200
commitd86a7374ea465ea23ea6e314ea06a48be7fb8663 (patch)
tree52db57b064fd4ce2ef8e89983700cc14ac134c1c
parent87bd30f96a52e1e5d3603528610ffcc486d2054a (diff)
Done, have to test now.
-rw-r--r--.gitignore2
-rwxr-xr-xSilicium/Topic.py3
-rw-r--r--Utilities/AccountManager.py107
-rwxr-xr-xUtilities/CacheManager.py (renamed from SiliciumCache/__init__.py)16
-rw-r--r--Utilities/__init__.py26
-rw-r--r--ids/.gitkeep0
-rwxr-xr-xmain.py30
-rwxr-xr-xregister.py66
8 files changed, 237 insertions, 13 deletions
diff --git a/.gitignore b/.gitignore
index 08ea181..8955169 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,4 @@
__pycache__
/cache.p
+/config.p
+/ids/*
diff --git a/Silicium/Topic.py b/Silicium/Topic.py
index 423e1c6..94bfec3 100755
--- a/Silicium/Topic.py
+++ b/Silicium/Topic.py
@@ -42,6 +42,9 @@ class Topic:
self.updater = updater
self.updated = updated
+ def link(self):
+ return sili_base + '/viewtopic.php?t={}'.format(self.id)
+
def __repr__(self):
rep = '<Silicium Topic {}'.format(self.id)
if self.posted:
diff --git a/Utilities/AccountManager.py b/Utilities/AccountManager.py
new file mode 100644
index 0000000..daad76d
--- /dev/null
+++ b/Utilities/AccountManager.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#******************************************************************************
+# Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1301, USA.
+#******************************************************************************
+""" The account manager for the Silicium Bot.
+ Manages Mastodon and Twitter accounts.
+"""
+
+import os, pickle
+from mastodon import Mastodon
+
+__all__ = ["AccountManager"]
+_VER = 'ohmygoditsmickbumhole'
+
+class AccountManager:
+ def __init__(self, path, ids_folder):
+ self.__path = path
+ self.__fold = ids_folder
+ self.__mastodon_app = None
+ self.__mastodon_users = {}
+ try:
+ data = pickle.load(open(self.__path, 'rb'))
+ if type(data) == dict and 'ver' in data and data['ver'] == _VER:
+ self.__mastodon_app = data["mastodon-app"]
+ if self.__mastodon_app:
+ self.__mastodon_users = data["mastodon-users"]
+ except:
+ pass
+
+ def save(self):
+ data = {'ver': _VER, 'mastodon-app': self.__mastodon_app,
+ 'mastodon-users': self.__mastodon_users}
+ pickle.dump(data, open(self.__path, 'wb'))
+
+ def mastodon_delete_app(self):
+ if not self.__mastodon_app:
+ return
+
+ for key in self.__mastodon_users:
+ try: os.remove(key)
+ except FileNotFoundError: pass
+ self.__mastodon_users = []
+
+ try: os.remove(self.__mastodon_app[0])
+ except FileNotFoundError: pass
+ self.__mastodon_app = None
+
+ self.save()
+
+ def mastodon_create_app(self, base):
+ app_id = 'mastodon_app.secret'
+
+ self.mastodon_delete_app()
+ Mastodon.create_app('Silicium.org Bot',
+ api_base_url = base,
+ to_file = os.path.join(self.__fold, app_id))
+ self.__mastodon_app = (app_id, base)
+ self.save()
+
+ def mastodon_connect(self, name, password):
+ if not self.__mastodon_app:
+ raise Exception("You need to create an application first!")
+ if name in self.__mastodon_users:
+ raise Exception("This user is already connected!")
+
+ user_id = 'mastodon_user_'
+ user_id += ''.join(c for c in name.replace('@', 'AT') if c in \
+ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_')
+ user_id += '.secret'
+
+ m = Mastodon(
+ client_id = os.path.join(self.__fold, self.__mastodon_app[0]),
+ api_base_url = self.__mastodon_app[1])
+ m.log_in(
+ name, password,
+ to_file = os.path.join(self.__fold, user_id)
+ )
+
+ self.__mastodon_users[name] = user_id
+ self.save()
+
+ def post(self, message):
+ if self.__mastodon_app:
+ mapp = os.path.join(self.__fold, self.__mastodon_app[0])
+ mbase = self.__mastodon_app[1]
+ for user in self.__mastodon_users:
+ muser = os.path.join(self.__fold, self.__mastodon_users[user])
+ Mastodon(client_id = mapp, api_base_url = mbase,
+ access_token = muser).toot(message)
+
+# End of file.
diff --git a/SiliciumCache/__init__.py b/Utilities/CacheManager.py
index 8735ce2..d1eaa1d 100755
--- a/SiliciumCache/__init__.py
+++ b/Utilities/CacheManager.py
@@ -25,6 +25,7 @@
import pickle, datetime
import Silicium
+__all__ = ["CacheManager"]
_VER = 'magick'
class CacheManager:
@@ -34,7 +35,7 @@ class CacheManager:
self.topics = []
try:
data = pickle.load(open(self.__path, 'rb'))
- if data['ver'] == _VER:
+ if type(data) == dict and 'ver' in data and data['ver'] == _VER:
self.forums = data['forums']
self.topics = data['topics']
except: pass
@@ -81,14 +82,15 @@ class CacheManager:
self.topics.extend(topics)
self.save()
- def get_topic(self):
- if not topics: return None
- return topics.pop()
+ def __iter__(self):
+ while self.topics:
+ yield self.topics[0]
+ self.topics.pop(0)
- def get_topics(self):
- topics = self.topics
+ def update(self):
+ self.refresh()
self.topics = []
- return topics
+ self.save()
def refresh(self):
self.__refresh_forum(Silicium.Forum(0))
diff --git a/Utilities/__init__.py b/Utilities/__init__.py
new file mode 100644
index 0000000..bafd3a9
--- /dev/null
+++ b/Utilities/__init__.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#******************************************************************************
+# Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1301, USA.
+#******************************************************************************
+""" Include all of the utilities for the bot. """
+
+from .AccountManager import *
+from .CacheManager import *
+
+# End of file.
diff --git a/ids/.gitkeep b/ids/.gitkeep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/ids/.gitkeep
diff --git a/main.py b/main.py
index 20fb9f2..e849c78 100755
--- a/main.py
+++ b/main.py
@@ -22,24 +22,42 @@
Refer to `README.md` if you have any questions on the project.
"""
-import os, argparse
-import SiliciumCache
+import os, time, argparse
+from Utilities import *
if __name__ == "__main__":
cache_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
'cache.p'))
+ config_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
+ 'config.p'))
+ ids_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
+ 'ids'))
# Parse the arguments.
argparser = argparse.ArgumentParser()
argparser.add_argument('--cache', dest='cache',
help='Cache path.', default=cache_path)
+ argparser.add_argument('--config', dest='config',
+ help='Config path.', default=config_path)
args = argparser.parse_args()
+ # Fire up the account manager.
+ mgr = AccountManager(config_path, ids_path)
+
# Make the cache manager, refresh.
- cache = SiliciumCache.CacheManager(args.cache)
- cache.refresh()
- print(cache.topics)
+ print("[+] Updating initial cache.")
+ cache = CacheManager(args.cache)
+ cache.update()
+
+ while True:
+ time.sleep(5)
+ print("[+] Refreshing cache..")
+ cache.refresh()
- # TODO: Mastodon and stuff.
+ for topic in cache:
+ print("[+] Publishing post for topic {}".format(topic.id))
+ msg = "Nouveau topic par {} : {}\n{}".format(topic.poster.name,
+ topic.title, topic.link())
+ mgr.post(msg)
# End of file.
diff --git a/register.py b/register.py
new file mode 100755
index 0000000..e588762
--- /dev/null
+++ b/register.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#******************************************************************************
+# Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+# MA 02110-1301, USA.
+#******************************************************************************
+""" Register an account for various things.
+ Mainly Mastodon for now, but can also support Twitter in the future.
+"""
+
+import os, argparse
+from Utilities import *
+
+if __name__ == '__main__':
+ config_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
+ 'config.p'))
+ ids_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
+ 'ids'))
+
+ # Parse the arguments.
+ argparser = argparse.ArgumentParser()
+ argparser.add_argument('--config', dest='config',
+ help='Config path.', default=config_path)
+ subs = argparser.add_subparsers(title='subcommands', dest='command',
+ metavar='<command>')
+
+ mca = subs.add_parser('mastodon-create',
+ help='Register a Mastodon app.')
+ mca.add_argument('base', help='The base URL for the instance.')
+
+ mc = subs.add_parser('mastodon-connect',
+ help='Connect to a Mastodon account.')
+ mc.add_argument('name', help='The username.')
+ mc.add_argument('password', help='The user password.')
+
+ tt = subs.add_parser('test-post',
+ help='Try to post to see if it is connected.')
+ tt.add_argument('status', help='The status to post.',
+ default="I'm hacking into their system!")
+
+ args = argparser.parse_args()
+
+ # Fire up the account manager.
+ mgr = AccountManager(config_path, ids_path)
+ if args.command == 'mastodon-create':
+ mgr.mastodon_create_app(args.base)
+ elif args.command == 'mastodon-connect':
+ mgr.mastodon_connect(args.name, args.password)
+ elif args.command == 'test-post':
+ mgr.post(args.status)
+
+# End of file.