class Bot(object): def __init__(self): self._client = SlackClient(settings.API_TOKEN, bot_icon=settings.BOT_ICON if hasattr( settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr( settings, 'BOT_EMOJI') else None) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins, settings.ERRORS_TO) def run(self): self._plugins.init_plugins() self._dispatcher.start() if not self._client.connected: self._client.rtm_connect() _thread.start_new_thread(self._keepactive, tuple()) logger.info('connected to slack RTM api') self._dispatcher.loop() def _keepactive(self): logger.info('keep active thread started') while True: time.sleep(30 * 60) self._client.ping()
def test_init_with_timeout(): client = SlackClient(None, connect=False) assert client.webapi.api.timeout == 10 # seconds default timeout expected_timeout = 42 # seconds client = SlackClient(None, connect=False, timeout=expected_timeout) assert client.webapi.api.timeout == expected_timeout
def __init__(self): super(ReportPublisher, self).__init__() self.setDaemon(False) self._db_context = DBContext() self._slackclient = SlackClient(API_TOKEN) self._should_stop = False self._interval = 3600
class Bot(object): def __init__(self): self._client = SlackClient( settings.API_TOKEN, bot_icon=settings.BOT_ICON if hasattr(settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr(settings, 'BOT_EMOJI') else None ) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins, settings.ERRORS_TO) def run(self): self._plugins.init_plugins() self._dispatcher.start() self._client.rtm_connect() _thread.start_new_thread(self._keepactive, tuple()) logger.info('connected to slack RTM api') self._dispatcher.loop() def _keepactive(self): logger.info('keep active thread started') while True: time.sleep(30 * 60) self._client.ping()
def __init__(self): super(WithdrawalExecutor, self).__init__() self.setDaemon(False) self._db_context = DBContext() self._slackclient = SlackClient(API_TOKEN) self._should_stop = False self._withdrawal_interval = 1
def __init__(self): self._client = SlackClient(settings.API_TOKEN, bot_icon=settings.BOT_ICON if hasattr( settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr( settings, 'BOT_EMOJI') else None) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins)
def __init__(self, api_token=None): if api_token is None: api_token = settings.API_TOKEN self._client = SlackClient(api_token, bot_icon=settings.BOT_ICON if hasattr( settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr( settings, 'BOT_EMOJI') else None) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins) self._stop = threading.Event()
def __init__(self): self._client = SlackClient( CONFIG.slack_api_token, timeout=settings.TIMEOUT if hasattr(settings, 'TIMEOUT') else None, bot_icon=settings.BOT_ICON if hasattr(settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr(settings, 'BOT_EMOJI') else None) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins, settings.ERRORS_TO)
def __init__(self): self._client = SlackClient( settings.API_TOKEN, bot_icon = settings.BOT_ICON if hasattr(settings, 'BOT_ICON') else None, bot_emoji = settings.BOT_EMOJI if hasattr(settings, 'BOT_EMOJI') else None ) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins)
def run(): # pragma: no cover """Start the dispatcher running.""" slack_client = SlackClient(settings.SLACKBOT_API_TOKEN) while True: run_once(slack_client, job_configs.config) time.sleep(1)
def loop(): """ 議論終了コマンドが送信されるまでメッセージの書き出しを行う関数 """ client = SlackClient(API_TOKEN) # ユーザーidからユーザー名を取得するため user_dict = get_user_dict() keys = [k for k, v in user_dict.items() if v == 'comhelper'] comhelper_user_id = keys[0] return_flag = True # 議論終了コマンドが送信されるまでループを続ける while return_flag: events = SlackClient.rtm_read(client) for event in events: event_type = event.get('type') if event_type == 'message': message_text = event.get('text') if message_text == '<@' + comhelper_user_id + "> 議論を終了して": # 議論終了コマンドが送信されたらループを抜ける return_flag = False else: # ユーザー名を確認しつつ,メッセージをテキストファイルに一時保存 send_user_id = event.get('user') send_user_name = user_dict[send_user_id] add_commit_message = [] add_commit_message.append('echo "' + send_user_name + ': ' + message_text + '" >> commit.txt') try: cmd_return = subprocess.run(add_commit_message, shell=True) except subprocess.SubprocessError: return 'echo >> commit.txt の実行でエラーが発生しました。' time.sleep(1) return '議論を終了しました!\n次の議論開始前にコミットしてください。'
class Bot(object): def __init__(self): self._client = SlackClient(settings.API_TOKEN) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins) def run(self): self._plugins.init_plugins() self._dispatcher.start() self._client.rtm_connect() thread.start_new_thread(self._keepactive, tuple()) logger.info('connected to slack RTM api') self._dispatcher.loop() def _keepactive(self): logger.info('keep active thread started') while True: time.sleep(30 * 60) self._client.ping()
def __init__(self, api_token=None): if api_token is None: api_token = settings.API_TOKEN self._client = SlackClient( api_token, bot_icon = settings.BOT_ICON if hasattr(settings, 'BOT_ICON') else None, bot_emoji = settings.BOT_EMOJI if hasattr(settings, 'BOT_EMOJI') else None ) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins) self._stop = threading.Event()
class Bot(object): def __init__(self, api_token=None): if api_token is None: api_token = settings.API_TOKEN self._client = SlackClient(api_token, bot_icon=settings.BOT_ICON if hasattr( settings, 'BOT_ICON') else None, bot_emoji=settings.BOT_EMOJI if hasattr( settings, 'BOT_EMOJI') else None) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins) self._stop = threading.Event() def run(self): self._plugins.init_plugins() self._dispatcher.start() self._client.rtm_connect() thread.start_new_thread(self._keepactive, tuple()) logger.info('Connected to slack RTM api') self._dispatcher.loop() def stop(self): self._stop.set() self._dispatcher.stop() def send_message(self, channel, message, **kwargs): """ Send a message using the web API """ logger.info("Send to %s: %s" % (channel, message)) self._client.webapi.chat.post_message(channel, message, as_user=True, **kwargs) def _keepactive(self): logger.info('Start heartbeat thread') while not self._stop.isSet(): self._stop.wait(30.0 * 60) self._client.ping() logger.info("Stop heartbeat thread")
def report_to_slack(cls, msg, file_path): try: slack_client = SlackClient(API_TOKEN) classname = cls.__class__.__name__ slack_client.send_message(SLACK_CHANNEL, f"[{classname}] : {msg}") slack_client.upload_file(SLACK_CHANNEL, "image", file_path, None) except: pass
class Bot(object): def __init__(self, api_token=None): if api_token is None: api_token = settings.API_TOKEN self._client = SlackClient( api_token, bot_icon = settings.BOT_ICON if hasattr(settings, 'BOT_ICON') else None, bot_emoji = settings.BOT_EMOJI if hasattr(settings, 'BOT_EMOJI') else None ) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins) self._stop = threading.Event() def run(self): self._plugins.init_plugins() self._dispatcher.start() self._client.rtm_connect() thread.start_new_thread(self._keepactive, tuple()) logger.info('Connected to slack RTM api') self._dispatcher.loop() def stop(self): self._stop.set() self._dispatcher.stop() def send_message(self, channel, message, **kwargs): """ Send a message using the web API """ logger.info("Send to %s: %s" % (channel,message)) self._client.webapi.chat.post_message(channel, message, as_user=True, **kwargs) def _keepactive(self): logger.info('Start heartbeat thread') while not self._stop.isSet(): self._stop.wait(30.0 * 60) self._client.ping() logger.info("Stop heartbeat thread")
def handle_message(text, expect_reaction=True): client = SlackClient("api_token", connect=False) plugins = PluginsManager() dispatcher = MessageDispatcher(client, plugins, None) msg = [ "respond_to", {"text": text, "channel": "channel", "ts": str(time.mktime(T0.timetuple()))}, ] if expect_reaction: with assert_slack_client_reacts_to_message(): dispatcher.dispatch_msg(msg) else: with assert_slack_client_doesnt_react_to_message(): dispatcher.dispatch_msg(msg)
def handle_message(text, *, category="respond_to", expect_reaction=True): client = SlackClient("api_token", connect=False) plugins = PluginsManager() plugins.init_plugins() dispatcher = MessageDispatcher(client, plugins, None) msg = [ category, { "text": text, "channel": "channel", "ts": TS }, ] if expect_reaction: with assert_slack_client_reacts_to_message(): dispatcher.dispatch_msg(msg) else: with assert_slack_client_doesnt_react_to_message(): dispatcher.dispatch_msg(msg)
def handle_callback_webhook(): """Respond to callback webhook.""" try: channel = request.args["channel"] thread_ts = request.args["thread_ts"] token = request.args["token"] except KeyError: abort(400) try: timestamp, signature = token.split(":", 1) except ValueError: abort(400) try: validate_hmac( timestamp.encode("utf8"), settings.EBMBOT_WEBHOOK_SECRET, signature.encode("utf8"), max_age=settings.EBMBOT_WEBHOOK_TOKEN_TTL, ) except InvalidHMAC: abort(403) try: data = json.loads(request.data.decode()) except json.decoder.JSONDecodeError: abort(400) try: message = data["message"] except KeyError: abort(400) client = SlackClient(settings.SLACKBOT_API_TOKEN) notify_slack(client, channel=channel, thread_ts=thread_ts, message=message) return ""
f"""\ ``` {new_line.join(texts)} ```""" ) def fake_message(client: SlackClient, text: str, *, channel: str) -> Message: data = {"text": text, "channel": channel} return Message(client, data) logging.basicConfig(level=logging.DEBUG) dotenv.load_dotenv(verbose=True) token = os.environ["SLACKBOT_API_TOKEN"] client = SlackClient(token) client.rtm_connect() # message = fake_message(client, "$hello") # hello_send(message) res = client.webapi.channels.list(exclude_archived=True) channels = {ch["name"]: ch["id"] for ch in res.body["channels"]} message = fake_message(client, "$hello --name=world", channel=channels["random"]) print("@@", hello_send(message)) import time time.sleep(1) print("end")
class WithdrawalExecutor(threading.Thread): """ 送金依頼を監視し、送金するクラス """ def __init__(self): super(WithdrawalExecutor, self).__init__() self.setDaemon(False) self._db_context = DBContext() self._slackclient = SlackClient(API_TOKEN) self._should_stop = False self._withdrawal_interval = 1 def run(self): """ スレッドを開始します。 """ self._should_stop = False while not self._should_stop: start_time = time.time() self._db_context.session.expire_all() # 休息中の送金元リスト updated_from = (datetime.datetime.now() - datetime.timedelta(seconds=60)).astimezone( timezone('UTC')) rest_address = self._db_context.session \ .query(distinct(WithdrawalRequest.from_address)) \ .filter(WithdrawalRequest.updated_at >= updated_from) \ .all() rest_address = list(map(lambda x: x[0], rest_address)) # 未着手の送金依頼を取得する prompt = self._db_context.session.query(WithdrawalRequest) \ .filter(WithdrawalRequest.is_success.is_(None)) \ .filter(WithdrawalRequest.from_address.notin_(rest_address)) \ .order_by(asc(WithdrawalRequest.symbol), asc(WithdrawalRequest.id)) \ .first() # 未着手の送金依頼を取得できた場合 if prompt: # 送金元・送金先・送金目的が同一の依頼を再取得する requests = self._db_context.session.query(WithdrawalRequest) \ .filter(WithdrawalRequest.is_success.is_(None)) \ .filter(WithdrawalRequest.from_address == prompt.from_address) \ .filter(WithdrawalRequest.to_address == prompt.to_address) \ .filter(WithdrawalRequest.purpose == prompt.purpose) \ .order_by(asc(WithdrawalRequest.id)) \ .all() # 未着手の送金依頼を取得できない場合 else: # エラーとなった送金依頼を取得する prompt = self._db_context.session.query(WithdrawalRequest) \ .filter(WithdrawalRequest.is_success == False) \ .order_by(asc(WithdrawalRequest.id)) \ .first() if prompt: requests = [prompt] else: requests = [] if len(requests) > 0: # 送金元ユーザーを取得する if requests[0].from_address == ITB_FOUNDATION_ADDRESS: from_user = None from_address = ITB_FOUNDATION_ADDRESS from_privkey = ITB_FOUNDATION_PRIVKEY else: from_user = User.get_user_from_eth_address( self._db_context, requests[0].from_address) from_address = from_user.eth_address from_privkey = from_user.eth_privkey # 送金先ユーザーを取得する to_user = User.get_user_from_eth_address( self._db_context, requests[0].to_address) # 送金額を集計する total_amount = sum(map(lambda x: x.amount, requests)) # 送金する wc = WalletController(from_address, from_privkey) is_success, tx_hash, error_reason = wc.send_to( requests[0].to_address, requests[0].symbol, total_amount) # 送金結果を反映する for request in requests: request.is_success = is_success request.tx_hash = tx_hash request.error_reason = error_reason request.updated_at = func.now() self._db_context.session.commit() # 送金結果を通知する if requests[0].purpose == "ガス代補充": pass elif requests[0].purpose == "新規登録ボーナス": # 送金先ユーザーに通知する if to_user.notification_enabled: channel_id = self._slackclient.open_dm_channel( to_user.slack_uid) if requests[0].is_success == True: self._slackclient.send_message( channel_id, str("新規登録ボーナスを獲得しました:laughing: (+{:.0f} ITB)\n" + "https://ropsten.etherscan.io/tx/{}"). format(total_amount, requests[0].tx_hash)) else: self._slackclient.send_message( channel_id, str("新規登録ボーナスの獲得に失敗しました:sob:\n" + "{}").format( requests[0].error_reason)) elif requests[0].purpose == "いいね!チップ": # 送金先ユーザーに通知する if to_user.notification_enabled: channel_id = self._slackclient.open_dm_channel( to_user.slack_uid) if requests[0].is_success == True: self._slackclient.send_message( channel_id, str("いいね!チップを獲得しました:laughing: (+{:.0f} ITB)\n" + "https://ropsten.etherscan.io/tx/{}"). format(total_amount, requests[0].tx_hash)) # 送金元ユーザーに通知する if from_user.notification_enabled: channel_id = self._slackclient.open_dm_channel( from_user.slack_uid) if requests[0].is_success == True: self._slackclient.send_message( channel_id, str("いいね!チップを送信しました:laughing: (-{:.0f} ITB)\n" + "https://ropsten.etherscan.io/tx/{}"). format(total_amount, requests[0].tx_hash)) else: self._slackclient.send_message( channel_id, str("いいね!チップの送信に失敗しました:sob:\n" + "{}").format( requests[0].error_reason)) elif requests[0].purpose == "グッドコミュニケーションボーナス": # 送金先ユーザーに通知する if to_user.notification_enabled: channel_id = self._slackclient.open_dm_channel( to_user.slack_uid) if requests[0].is_success == True: self._slackclient.send_message( channel_id, str("グッドコミュニケーションボーナスを獲得しました:laughing: (+{:.0f} ITB)\n" + "https://ropsten.etherscan.io/tx/{}"). format(total_amount, requests[0].tx_hash)) past_time = time.time() - start_time if past_time < self._withdrawal_interval: time.sleep(self._withdrawal_interval - past_time) def request_stop(self): """ スレッドの停止をリクエストします。 """ self._should_stop = True
def sendDM(self, text, target): sc = client(API_TOKEN) client.send_message(self=sc, channel=target, message=text)
def get_slack_client(): return SlackClient(API_TOKEN) if slack_client is None else slack_client
def sendDM(text, target): sc = client(API_TOKEN) client.send_message(channel=target, message=text)
def slack_client(): c = SlackClient(None, connect=False) c.channels = slackclient_data.CHANNELS c.users = slackclient_data.USERS return c
class ReportPublisher(threading.Thread): """ ITBトークンの利用状況に関するレポートを発行するクラス """ def __init__(self): super(ReportPublisher, self).__init__() self.setDaemon(False) self._db_context = DBContext() self._slackclient = SlackClient(API_TOKEN) self._should_stop = False self._interval = 3600 def run(self): """ スレッドを開始します。 """ self._should_stop = False while not self._should_stop: start_time = time.time() self._db_context.session.expire_all() # 現在時刻を取得する current_datetime = datetime.datetime.today().astimezone(timezone('Asia/Tokyo')) # 平日の場合 if current_datetime.weekday() in [0, 1, 2, 3, 4]: # 朝10時の場合 if current_datetime.hour == 10: for channel_id in REPORT_CHANNELS: self._slackclient.send_message( channel_id, "昨日のITBトークンの利用状況を報告します。" ) # 総幸福量(Gross Happiness)に関するレポートを発行する self.publish_grosshappiness(channel_id, current_datetime-datetime.timedelta(days=1)) # ITBカフェの売上高に関するレポートを発行する self.publish_sales(channel_id, current_datetime-datetime.timedelta(days=1)) past_time = time.time() - start_time if past_time < self._interval: time.sleep(self._interval - past_time) def publish_grosshappiness(self, channel_id: str, designated_date: datetime.datetime): """ いいね!総生産量に関するレポートを発行します。 """ date_from = datetime.datetime(*designated_date.timetuple()[:3]) date_to = date_from + datetime.timedelta(days=1) amount = self._db_context.session \ .query(func.sum(WithdrawalRequest.amount)) \ .filter(WithdrawalRequest.symbol == Symbol.ITB) \ .filter(WithdrawalRequest.updated_at >= date_from) \ .filter(WithdrawalRequest.updated_at < date_to) \ .all()[0][0] if amount is None: amount = Decimal("0") self._slackclient.send_message( channel_id, "昨日のいいね!総生産量は「{:.0f} ITB」でした。" .format(amount) ) def publish_sales(self, channel_id: str, designated_date: datetime.datetime): """ ITBカフェの売上高に関するレポートを発行します。 """ date_from = datetime.datetime(*designated_date.timetuple()[:3]) date_to = date_from + datetime.timedelta(days=1) amount = self._db_context.session \ .query(func.sum(ShopOrder.price)) \ .filter(ShopOrder.ordered_at >= date_from) \ .filter(ShopOrder.ordered_at < date_to) \ .all()[0][0] if amount is None: amount = Decimal("0") self._slackclient.send_message( channel_id, "昨日のITBカフェ売上高は「{:.0f} ITB」でした。" .format(amount) ) def request_stop(self): """ スレッドの停止をリクエストします。 """ self._should_stop = True
import os import time import re from slackbot.slackclient import SlackClient # instantiate Slack client slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) # starterbot's user ID in Slack: value is assigned after the bot starts up starterbot_id = None # constants RTM_READ_DELAY = 1 # 1 second delay between reading from RTM EXAMPLE_COMMAND = "do" MENTION_REGEX = "^<@(|[WU].+?)>(.*)" def parse_bot_commands(slack_events): """ Parses a list of events coming from the Slack RTM API to find bot commands. If a bot command is found, this function returns a tuple of command and channel. If its not found, then this function returns None, None. """ for event in slack_events: if event["type"] == "message" and not "subtype" in event: user_id, message = parse_direct_mention(event["text"]) if user_id == starterbot_id: return message, event["channel"] return None, None def parse_direct_mention(message_text):
def __init__(self): self._client = SlackClient(settings.API_TOKEN) self._plugins = PluginsManager() self._dispatcher = MessageDispatcher(self._client, self._plugins)
from plugins.gomisute.logs.LogHandler import LogHandler import configparser logger = LogHandler('service') conf = configparser.ConfigParser() conf.read('./config.ini') API_TOKEN = conf['slack']['BOT_USER_OAUTH_ACCESS_TOKEN'] attempt_user = conf['slack']['attempt_user'] endpoint = conf['chaplus']['endpoint'] chaplus_key = conf['chaplus']['api_key'] chaplus_dist = f'{endpoint}?apikey={chaplus_key}' client = SlackClient(API_TOKEN) @respond_to(r'^(?=.*[ごみ|ゴミ])(?!.*(終|代わ|更新))') def sendTrashDuty2525AND2721(message, *args): """ (ごみorゴミ)を含むメッセージに対し 両室の次回のごみ捨て当番をリプライする. Args: message (Message) : メッセージに関する情報を持ったクラスのインスタンス args (str) : respond_to()内の正規表現にマッチしたメッセージ本文 Returns: None """
import os import logging import time from slackbot.slackclient import SlackClient import dotenv logging.basicConfig(level=logging.DEBUG) dotenv.load_dotenv(verbose=True) token = os.environ["SLACKBOT_API_TOKEN"] client = SlackClient(token) client.rtm_connect() while True: events = client.rtm_read() for ev in events: print(ev) time.sleep(1) # {"type": "hello"} # {'type': 'user_typing', 'channel': 'C02M87T2E', 'user': '******'} # {'client_msg_id': 'de84cc41-17cb-4cf0-94ae-06ff52a1a8c1', 'suppress_notification': False, 'type': 'message', 'te # xt': 'hai', 'user': '******', 'team': 'T02M87T1A', 'blocks': [{'type': 'rich_text', 'block_id': 'QlOL', 'elem # ents': [{'type': 'rich_text_section', 'elements': [{'type': 'text', 'text': 'hai'}]}]}], 'user_team': 'T02M87T1A # ', 'source_team': 'T02M87T1A', 'channel': 'C02M87T2E', 'event_ts': '1577500892.003200', 'ts': '1577500892.003200 # '} # {'type': 'reaction_added', 'user': '******', 'item': {'type': 'message', 'channel': 'C02M87T2E', 'ts': '15775 # 00892.003200'}, 'reaction': 'cyclone', 'item_user': '******', 'event_ts': '1577500906.003300', 'ts': '1577500 # 906.003300'}
def do_job(job): slack_client = SlackClient("api_token", connect=False) job_dispatcher = JobDispatcher(slack_client, job, config) job_dispatcher.do_job()
import os import logging import time from slackbot.slackclient import SlackClient import dotenv logging.basicConfig(level=logging.DEBUG) dotenv.load_dotenv(verbose=True) token = os.environ["SLACKBOT_API_TOKEN"] client = SlackClient(token) client.ping() client.send_message("#random", "hello") client.rtm_send_message("#random", "hello from RTM") print("hai") time.sleep(1) print("hoi")