def print_all_menus(*, only_today: bool = True, report_to_slack: bool = True):
    loop = asyncio.get_event_loop()

    tasks = asyncio.wait([get_week_menu(Restaurants.ANTARO),
                          get_week_menu(Restaurants.PERLA)], timeout=10)

    finished_tasks = loop.run_until_complete(tasks)[0]

    results: Dict[Restaurants, Dict[datetime.date, Tuple[str, List[str]]]] = {
        task.result()[0]: task.result()[1] for task in finished_tasks
    }

    if only_today:
        results = {
            restaurant: {
                day: menu for day, menu in week_menu.items() if (day == datetime.date.today())
            } for restaurant, week_menu in results.items()
        }

    for restaurant, week_menu in results.items():  # type: Restaurants, Dict[datetime.date, Tuple[str, List[str]]]
        print(f"Restaurant: {restaurant.name}")
        for day, (day_name, menu) in week_menu.items():
            print(f"\t{day_name}, {day:%d.%m.%Y}:")
            for item in menu:
                print(f"\t\t- {item}")

    if report_to_slack:
        sc = SlackClient(None, "food", token_env_var="SLACK_TOKEN_REPORTS")
        sc.post_menu(results)
Esempio n. 2
0
def team_log_save(token):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    sc = SlackClient(token)
    team = sc.team_info()
    db = SlackStorage(team["name"])

    cl = sc.channels_list()
    channels = [c['name'] for c in cl]

    wrote_count = 0
    for name in channels:
        # get the latest timestamp
        since = db.get_latest_timestamp(name)

        # get all messages from timestamp
        messages = sc.get_messages(name, since)
        if 0 < len(messages):
            logger.info("#{n} since {s} got {t} messages".format(n=name,
                                                                s=since,
                                                                t=len(messages)))
        else:
            continue

        # save message logs
        db.save(name, messages)
        logger.info('wrote {c} messages for #{n}'.format(c=len(messages),
                                                        n=name))

    db.close()
    logger.info('{c} messages saved in total {n} channels'.format(c=wrote_count,
                                                                  n=len(channels)))
Esempio n. 3
0
def get_members_dict(token):
    if os.path.exists("members.yaml"):
        with open("members.yaml") as f:
            return yaml.load(f)
    sc = SlackClient(token)
    members = sc.users_list()['members']
    member_dict = {}
    for member in members:
        member_dict[member['id']] = member
    with open("members.yaml", "w") as f:
        yaml.dump(member_dict, f)
    return member_dict
Esempio n. 4
0
    def __init__(self):
        self.relay_client = RelayClient()
        self.relay_client.set_on_buffer_line_added_callback(
            self._on_buffer_line_added)
        self.relay_client.set_on_buffer_opened_callback(self._on_buffer_opened)
        self.relay_client.set_on_buffer_closing_callback(
            self._on_buffer_closing)
        self.relay_client.set_on_post_setup_buffers_callback(
            self._on_post_setup_buffers)
        self.relay_client.init()

        self.slack_client = SlackClient()
        self.slack_client.set_message_callback(self._on_slack_message)
        self.slack_client.create_dm_channels([
            buffer
            for _, buffer in self.relay_client.get_direct_message_buffers()
        ], self.s2w_dm_channels_map)
def main(args):
    ns = create_parser(args)
    logger = config_logger()
    logger.setLevel(ns.loglevel)
    loglevel = logging.getLevelName(logger.getEffectiveLevel())
    app_start_time = dt.now()
    logger.info('\n------------------------------------------------\n'
                f'          Running {__file__}\n'
                f'          Started on {app_start_time.isoformat()}\n'
                f'          PID is {os.getpid()}\n'
                f'          loglevel is {loglevel}\n'
                '-------------------------------------------------')

    with SlackClient(bot_user_token=os.environ['BOT_USER_TOKEN'],
                     bot_id=os.environ['BOT_USER_ID']) as bot:
        bot.run()

    uptime = dt.now() - app_start_time
    logger.info('\n--------------------------------------------\n'
                f'         Stopped {__file__}\n'
                f'         Uptime was {str(uptime)}\n'
                '---------------------------------------------\n')
Esempio n. 6
0
def main(args):
    log_banner_start()
    start_time = datetime.datetime.now()

    # parse arguments from command-line
    parser = create_parser(args)
    args_ns = parser.parse_args()
    logger.info('Command-line arguments recieved and parsed')

    # set log level for program
    log_levels = [
        logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
        logging.CRITICAL
    ]
    logger.setLevel(log_levels[int(args_ns.log_lvl)])
    if args:
        logger.info('Custom log-level set in accordance with ' +
                    'command-line argument provided')

    # signal handler configuration
    config_signal_handlers()

    # connect to Twitter Client
    with TwitterClient(
            consumer_key=os.environ['CONSUMER_KEY'],
            consumer_secret=os.environ['CONSUMER_SECRET'],
            access_token=os.environ['ACCESS_TOKEN'],
            access_token_secret=os.environ['ACCESS_TOKEN_SECRET']) as twitter:
        logger.info('Twitter client connected')

        # connect to Slack
        slack = SlackClient(oauth_token=os.environ['SLACK_TOKEN'])
        logger.info('Slack client connected')

        # connect Twitter Client to Slack Client to each other
        slack.register_twitter_client(twitter)
        logger.info('Slack and Twitter clients connected to each other')

        slack.run()

        log_banner_stop(start_time)
Esempio n. 7
0
from scrapers.velryba_scraper import VelrybaScraper
from slack_client import SlackClient
import os

if __name__ == '__main__':
    scrapers = [
        KarluvSklepScraper(),
        SrdcovkaScraper(),
        VelrybaScraper(),
        SerialBurgersScraper(),
        DynamoScraper(),
        JinaKrajinaScraper(),
        ChilliPointScraper(),
        GranFierroScraper(),
        KathmanduScraper(),
        TheNestScraper(),
        LemonLeafScraper(),
        # LaLocaScraper(),
        EstrellaScraper(),
    ]

    client = SlackClient(os.environ['SLACK_ACCESS_TOKEN'], '#prague_lunch')

    for scraper in scrapers:
        client.add_menu(scraper.name,
                        scraper.dish_array,
                        restaurant_icon=scraper.icon,
                        color=scraper.color,
                        link=scraper.link)

    client.write_menu()
Esempio n. 8
0
from price_bot import PriceBot
from slack_client import SlackClient

price_bot = PriceBot()
slacK_client = SlackClient()

price = price_bot.get_price()
print(price)

if price < 200:
    msg = 'Item is available at £{}'.format(price)
    slack_client.call_slack(msg)

#msg = input('Enter message: ')
#slack_client.call_slack(msg)
Esempio n. 9
0
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = config('DATABASE_URL').replace(
    'postgres:', 'postgresql:')  # noqa: E501
# Database
db.init_app(app)
with app.app_context():
    db.create_all()

# Slack Bolt
slack_app = App(token=config('BOT_USER_OAUTH_TOKEN'),
                signing_secret=config('SLACK_SIGNING_SECRET'))
handler = SlackRequestHandler(slack_app)

# Clients
slack_client = SlackClient(config('BOT_USER_OAUTH_TOKEN'))
translation_client = TranslationClient()


def check_if_thread_was_already_translated_and_persist_slack_reaction(
        channel_id: str,  # noqa: E501
        thread_timestamp: str,  # noqa: E501
        reaction: str) -> bool:  # noqa: E501
    with app.app_context():
        # Check if there was any reaction already
        slack_reaction_count = db.session.query(SlackReaction).\
            filter_by(channel_id=channel_id).\
            filter_by(thread_timestamp=thread_timestamp).\
            filter_by(reaction=reaction).\
            count()
Esempio n. 10
0
import logging
import config
from news_api import NewsApi
from slack_client import SlackClient

logging.basicConfig(filename=config.LOGFILE,
                    level=logging.INFO,
                    format='%(asctime)s %(levelname)-8s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')


def main(news_api, slack_client):
    for query in config.QUERIES:
        result = news_api.obtain_top_headlines(query)
        headlines = result['articles'][:query.headline_limit]
        slack_client.send_messages(query.name, headlines, query.webhook_url)


if __name__ == "__main__":
    main(NewsApi(), SlackClient())
Esempio n. 11
0
class WeeChatRelay2Slack:
    relay_client: RelayClient
    slack_client: SlackClient

    # Slack <> WeeChat channel map
    s2w_dm_channels_map = {}

    def __init__(self):
        self.relay_client = RelayClient()
        self.relay_client.set_on_buffer_line_added_callback(
            self._on_buffer_line_added)
        self.relay_client.set_on_buffer_opened_callback(self._on_buffer_opened)
        self.relay_client.set_on_buffer_closing_callback(
            self._on_buffer_closing)
        self.relay_client.set_on_post_setup_buffers_callback(
            self._on_post_setup_buffers)
        self.relay_client.init()

        self.slack_client = SlackClient()
        self.slack_client.set_message_callback(self._on_slack_message)
        self.slack_client.create_dm_channels([
            buffer
            for _, buffer in self.relay_client.get_direct_message_buffers()
        ], self.s2w_dm_channels_map)

    def _on_buffer_line_added(self, response: dict, run_async: bool = False):
        if not run_async:
            threading.Thread(target=self._on_buffer_line_added,
                             args=(response, True)).start()
            return

        buffer_pointer = response.get('buffer', '')
        message = response.get('message', '')
        tags_array = response.get('tags_array', [])

        is_generic_server_msg = bool({
            'irc_401', 'irc_402', 'irc_join', 'irc_kick', 'irc_mode',
            'irc_nick', 'irc_nick_back', 'irc_part', 'irc_topic', 'irc_quit'
        } & set(tags_array))
        is_privmsg = 'irc_privmsg' in tags_array

        if not any((is_generic_server_msg, is_privmsg)):
            return

        if buffer_pointer.startswith('gui_'):
            buffer = self.relay_client.wait_for_buffer_by_pointer(
                buffer_pointer)
        else:
            buffer = self.relay_client.wait_for_buffer_by_pointer(
                f'0x{buffer_pointer}')

        if buffer is None:
            logging.error(
                f'Timed out while waiting for buffer {buffer_pointer}')
            return

        if buffer.full_name in Config.Relay.Filters:
            for filter_tags in Config.Relay.Filters[buffer.full_name]:
                if all(x in tags_array for x in filter_tags.split('+')):
                    return

        buffer_name, msg = buffer.full_name, Utils.weechat_string_remove_color(
            message)

        if buffer_name not in Config.Global.Channels:
            buffer_name = Utils.get_slack_direct_message_channel_for_buffer(
                buffer_name)

            if buffer_name is not None:
                self.slack_client.wait_for_dm_channel(buffer_name)
        else:
            buffer_name = Config.Global.Channels[buffer_name]

        if buffer_name is not None:
            if is_generic_server_msg:
                self.slack_client.send_me_message(buffer_name, msg)
            elif is_privmsg:
                if 'irc_action' in tags_array:
                    self.slack_client.send_me_message(buffer_name, msg)
                else:
                    prefix = Utils.weechat_string_remove_color(
                        response.get('prefix', ''))
                    self.slack_client.send_message(buffer_name, prefix, msg)

    def _on_buffer_opened(self, response: dict, run_async: bool = False):
        if not run_async:
            threading.Thread(target=self._on_buffer_opened,
                             args=(response, True)).start()
            return

        full_name = response.get('full_name', '')
        buffer_name = Utils.get_slack_direct_message_channel_for_buffer(
            full_name)

        if buffer_name is None:
            return

        if buffer_name not in self.slack_client.last_dm_channels:
            logging.info(f'Adding DM channel: {buffer_name}')

            self.slack_client.create_dm_channels(
                self.slack_client.last_dm_channels + [buffer_name],
                self.s2w_dm_channels_map)

        self.s2w_dm_channels_map[buffer_name] = full_name

    def _on_buffer_closing(self, response: dict, run_async: bool = False):
        if not run_async:
            threading.Thread(target=self._on_buffer_closing,
                             args=(response, True)).start()
            return

        full_name = response.get('full_name', '')
        buffer_name = Utils.get_slack_direct_message_channel_for_buffer(
            full_name)

        if buffer_name is None:
            return

        if buffer_name in self.slack_client.last_dm_channels:
            logging.info(f'Closing DM channel: {buffer_name}')

            self.slack_client.create_dm_channels([
                c
                for c in self.slack_client.last_dm_channels if c != buffer_name
            ], self.s2w_dm_channels_map)

        if buffer_name in self.s2w_dm_channels_map:
            del self.s2w_dm_channels_map[buffer_name]

    def _on_slack_message(self, channel: str, msg: str):
        weechat_channel = self.s2w_dm_channels_map[
            channel] if channel in self.s2w_dm_channels_map else None

        if weechat_channel is not None:
            self.relay_client.input(weechat_channel, msg)
        else:
            for weechat_channel, slack_channel in Config.Global.Channels.items(
            ):
                if slack_channel == channel:
                    self.relay_client.input(weechat_channel, msg)
                    break

    def _on_post_setup_buffers(self):
        for buffer in self.relay_client.buffers:
            buffer_name = Utils.get_slack_direct_message_channel_for_buffer(
                buffer.full_name)

            if buffer_name is not None:
                self.s2w_dm_channels_map[buffer_name] = buffer.full_name

    def run(self):
        threads = [
            *self.relay_client.tasks(),
            *self.slack_client.tasks(),
        ]

        [thread.start() for thread in threads]

        try:
            [thread.join() for thread in threads]
        except KeyboardInterrupt:
            logging.info('Bye!')

            # Kill existing threads
            for thread in threads:
                thread.is_alive = False
                thread.join()