Update for aprsd 3.0.0

This commit is contained in:
Hemna 2022-12-29 15:23:19 -05:00
parent 25e18a55d2
commit 827832ae33
6 changed files with 152 additions and 15 deletions

View File

@ -0,0 +1,9 @@
import logging
from aprsd_twitter_plugin.conf import twitter
from oslo_config import cfg
CONF = cfg.CONF
twitter.register_opts(CONF)

View File

@ -0,0 +1,80 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
This is the single point of entry to generate the sample configuration
file for Nova. It collects all the necessary info from the other modules
in this package. It is assumed that:
* every other module in this package has a 'list_opts' function which
return a dict where
* the keys are strings which are the group names
* the value of each key is a list of config options for that group
* the nova.conf package doesn't have further packages with config options
* this module is only used in the context of sample file generation
"""
import collections
import importlib
import os
import pkgutil
LIST_OPTS_FUNC_NAME = "list_opts"
def _tupleize(dct):
"""Take the dict of options and convert to the 2-tuple format."""
return [(key, val) for key, val in dct.items()]
def list_opts():
opts = collections.defaultdict(list)
module_names = _list_module_names()
imported_modules = _import_modules(module_names)
_append_config_options(imported_modules, opts)
return _tupleize(opts)
def _list_module_names():
module_names = []
package_path = os.path.dirname(os.path.abspath(__file__))
for _, modname, ispkg in pkgutil.iter_modules(path=[package_path]):
if modname == "opts" or ispkg:
continue
else:
module_names.append(modname)
return module_names
def _import_modules(module_names):
imported_modules = []
for modname in module_names:
mod = importlib.import_module("aprsd_telegram_plugin.conf." + modname)
if not hasattr(mod, LIST_OPTS_FUNC_NAME):
msg = "The module 'aprsd_telegram_plugin.conf.%s' should have a '%s' "\
"function which returns the config options." % \
(modname, LIST_OPTS_FUNC_NAME)
raise Exception(msg)
else:
imported_modules.append(mod)
return imported_modules
def _append_config_options(imported_modules, config_options):
for mod in imported_modules:
configs = mod.list_opts()
for key, val in configs.items():
config_options[key].extend(val)

View File

@ -0,0 +1,44 @@
from oslo_config import cfg
telegram_group = cfg.OptGroup(
name="aprsd_telegram_plugin",
title="APRSD Telegram Plugin settings",
)
telegram_opts = [
cfg.StrOpt(
"callsign",
help="Callsign allowed to use Telegram! "
"For example, if you set this to WB4BOR then any"
"callsign starting with WB4BOR will be allowed to use this."
"This way WB4BOR-1 can tweet from this instance.",
),
cfg.StrOpt(
"apiKey",
help="Your twitter apiKey"
"Information for creating your api keys is here: "
"https://developer.twitter.com/en/docs/authentication/oauth-1-0a/api-key-and-secret",
),
cfg.ListOpt(
"shortcuts",
help="List of shortcuts for sending telegram messages "
"For Exmaple: wb=hemna6969,cl=craigerl\n"
"Means use 'wb' to send a telegram message to hemna6969",
),
]
ALL_OPTS = (
telegram_opts
)
def register_opts(cfg):
cfg.register_group(telegram_group)
cfg.register_opts(ALL_OPTS, group=telegram_group)
def list_opts():
return {
telegram_group.name: ALL_OPTS,
}

View File

@ -3,12 +3,16 @@ import logging
import threading
import time
from aprsd import conf # noqa
from aprsd import objectstore, packets, plugin, threads
from oslo_config import cfg
from telegram.ext import Filters, MessageHandler, Updater
import aprsd_telegram_plugin
from aprsd_telegram_plugin import conf # noqa
CONF = cfg.CONF
LOG = logging.getLogger("APRSD")
@ -23,17 +27,15 @@ class TelegramUsers(objectstore.ObjectStoreMixin):
"""
_instance = None
data = {}
config = None
_shortcuts = {}
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.lock = threading.Lock()
cls._instance.config = kwargs["config"]
cls._instance.data = {}
if kwargs["config"].exists("services.telegram.shortcuts"):
cls._instance._shortcuts = kwargs["config"].get("services.telegram.shortcuts")
if CONF.aprsd_telegram_plugin.shortcuts:
cls._instance._shortcuts = CONF.aprsd_telegram_plugin.shortcuts
else:
cls._instance._shortcuts = None
cls._instance._init_store()
@ -87,16 +89,14 @@ class TelegramChatPlugin(plugin.APRSDRegexCommandPluginBase):
def setup(self):
self.enabled = True
# Do some checks here?
try:
self.config.check_option(["services", "telegram", "apiKey"])
except Exception as ex:
if not CONF.aprsd_telegram_plugin.apiKey:
LOG.error(f"Failed to find config telegram:apiKey {ex}")
self.enabled = False
return
token = self.config.get("services.telegram.apiKey")
token = CONF.aprsd_telegram_plugin.apiKey
self.users = TelegramUsers(config=self.config)
self.users = TelegramUsers()
self.users.load()
# self.bot = telegram.Bot(token=token)
@ -132,7 +132,7 @@ class TelegramChatPlugin(plugin.APRSDRegexCommandPluginBase):
# LOG.info(f"Chat {update.message.chat}")
# LOG.info(f"From {update.message.from.username} : ")
fromcall = self.config.get("aprs.login")
tocall = self.config.get("ham.callsign")
tocall = CONF.callsign
if update.message.chat.type == "private":
LOG.info(f"Username {update.message.chat.username} - ID {update.message.chat.id}")
@ -165,7 +165,7 @@ class TelegramChatPlugin(plugin.APRSDRegexCommandPluginBase):
def create_threads(self):
if self.enabled:
LOG.info("Starting TelegramThread")
return TelegramThread(self.config, self.updater)
return TelegramThread(self.updater)
def process(self, packet):
"""This is called when a received packet matches self.command_regex."""
@ -211,16 +211,15 @@ class TelegramChatPlugin(plugin.APRSDRegexCommandPluginBase):
class TelegramThread(threads.APRSDThread):
def __init__(self, config, updater):
def __init__(self, updater):
super().__init__(self.__class__.__name__)
self.config = config
self.past = datetime.datetime.now()
self.updater = updater
def stop(self):
self.thread_stop = True
self.updater.stop()
TelegramUsers(config=self.config).save()
TelegramUsers().save()
def loop(self):
"""We have to loop, so we can stop the thread upon CTRL-C"""

View File

@ -1,3 +1,4 @@
pbr
aprsd>=2.7.0
aprsd>=3.0.0
python-telegram-bot
oslo.config

View File

@ -19,6 +19,10 @@ description_file =
README.rst
summary = Ham Radio APRS APRSD plugin for Telegram IM service
[options.entry_points]
oslo.config.opts =
aprsd_telegram_plugin.conf = aprsd_telegram_plugin.conf.opts:list_opts
[global]
setup-hooks =
pbr.hooks.setup_hook