def _get_user_name(user_id):
"""
????? Slack ? user_id ????? username ???
Slacker ? users.list API ?????
- https://github.com/os/slacker
- https://api.slack.com/methods/users.info
"""
webapi = slacker.Slacker(settings.API_TOKEN)
response = webapi.users.info(user_id)
if response.body['ok']:
return response.body['user']['name']
else:
return ''
python类Slacker()的实例源码
def random_command(message, subcommand=None):
"""
???????????????????????????
- https://github.com/os/slacker
- https://api.slack.com/methods/channels.info
- https://api.slack.com/methods/users.getPresence
- https://api.slack.com/methods/users.info
"""
if subcommand == 'help':
botsend(message, '''- `$random`: ????????????????????????
- `$random active`: ????????active?????????????????
''')
return
# ???????????????
channel = message.body['channel']
webapi = slacker.Slacker(settings.API_TOKEN)
cinfo = webapi.channels.info(channel)
members = cinfo.body['channel']['members']
# bot ? id ???
bot_id = message._client.login_data['self']['id']
members.remove(bot_id)
member_id = None
while not member_id:
# ??????????????????
member_id = random.choice(members)
if subcommand == 'active':
# active ??????????? presence ?????
presence = webapi.users.get_presence(member_id)
if presence.body['presence'] == 'away':
members.remove(member_id)
member_id = None
user_info = webapi.users.info(member_id)
name = user_info.body['user']['name']
botsend(message, '{} ?????????'.format(name))
def __init__(self, config):
self.slack_api_token = config['slack_api_token']
self.slack_username = config['slack_username']
self.slack_channel = config['slack_channel']
self.slack_emote = config['slack_emote']
self.slack_shoutout = config['slack_shoutout']
self.slack_text_prefix = 'System Error {shoutout}: '.format(
shoutout=self.slack_shoutout)
self.slack = Slacker(self.slack_api_token)
def _login_with_token(self, token, identity_only):
try:
api_auth = Slacker(token).auth.test().body
assert api_auth['team_id'] == SLACK_TEAM_ID
except Error as err:
self.mongo.db.z_errors.insert_one({'_id': time.time(),
'ctx': 'auth.test',
'msg': str(err)})
return WebServer._basic_page('Auth error',
'Auth error: ' + str(err))
except AssertionError:
return WebServer._basic_page('Wrong team',
'Wrong team: ' + api_auth['team'])
return self._login_success(token, api_auth, identity_only)
def __init__(self, mongo, ctx, tokens, api_key):
self.mongo = mongo
self.log = SlackArchive.get_logger()
self.people = mongo_store.MongoStore(self.mongo.db.users, ctx)
self.streams = mongo_store.MongoStore(self.mongo.db.streams, ctx)
self.tokens = tokens
self.api_handle = Slacker(api_key)
self.scheduler = scheduler.Scheduler(ctx, mongo)
self._setup_scheduler()
self.scheduler.start()
def streams_fetch(self, token):
enc_key = self.tokens.get_key_by_known_token(token)
user_info = self.tokens[enc_key]
if user_info['full_access']:
try:
self.log.info('Fetch channels for %s', user_info['login'])
all_ch = Slacker(token).channels.list().body
SlackArchive.api_call_delay()
self.people.set_field(user_info['user'], 'channels',
SlackArchive._filter_channel_ids(all_ch))
self.update_streams(all_ch) # not a duplicate op: fight races
self.log.info('Fetch %s\'s private groups', user_info['login'])
groups = Slacker(token).groups.list().body
SlackArchive.api_call_delay()
self.people.set_field(user_info['user'], 'groups',
SlackArchive._filter_group_ids(groups))
self.update_streams(groups, user_info['user'])
self.log.info('Fetch direct msgs for %s', user_info['login'])
ims = Slacker(token).im.list().body
SlackArchive.api_call_delay()
self.people.set_field(user_info['user'], 'ims',
SlackArchive._filter_im_ids(groups, ims))
self.update_streams(ims, user_info['user'])
except Error as err:
self.mongo.db.z_errors.insert_one({'_id': time.time(),
'ctx': 'channels_fetch',
'msg': str(err)})
self.log.exception('Fetch streams error %s', str(err))
# full access was revoked
if str(err) == 'missing_scope':
self.tokens.set_field(enc_key, 'full_access', False)
def __init__(self):
# Open database connection
self.db = mysql.connect(host=ROJAK_DB_HOST, port=ROJAK_DB_PORT,
user=ROJAK_DB_USER, passwd=ROJAK_DB_PASS, db=ROJAK_DB_NAME)
self.cursor = self.db.cursor()
self.media = {}
try:
# Get media information from the database
self.logger.info('Fetching media information')
self.cursor.execute(sql_get_media, [self.name])
row = self.cursor.fetchone()
self.media['id'] = row[0]
self.media['last_scraped_at'] = row[1]
except mysql.Error as err:
self.logger.error('Unable to fetch media data: %s', err)
raise NotConfigured('Unable to fetch media data: %s' % err)
if ROJAK_SLACK_TOKEN != '':
self.is_slack = True
self.slack = Slacker(ROJAK_SLACK_TOKEN)
else:
self.is_slack = False
self.logger.info('Post error to #rojak-pantau-errors is disabled')
# Capture the signal spider_opened and spider_closed
# https://doc.scrapy.org/en/latest/topics/signals.html
def slackbot(text):
"""
Posts messages to Slack channel based on environment
"""
slack = Slacker(SLACK_TOKEN)
username = "DocPubBot"
icon_url = "http://autobinaryrobots.com/wp-content/uploads/2016/11/robot.png"
## map environment to related Slack channel
env_channels = {
"local": "#docpublocal",
"test": "#docpubtest",
"prod": "#docpubprod"
}
## set channel based on the environment
channel = env_channels[DOCPUBENV]
# channel = os.environ["MCCELECTIONSENV"]
## uses try statement in order to avoid requests package error:
# "Max retries exceeded with url"
try:
slack.chat.post_message(channel, text, username=username, link_names=True, icon_url=icon_url)
# return "Messaged posted: %s" % (text)
except:
print("WARNING: An error occured when trying to send the text to Slack.")
## outputs to command line so you can follow along/log there, especially when working locally
print(text)
def main(argv=None):
global VERBOSE
argv = sys.argv[1:] if argv is None else argv
args = parser.parse_args(argv)
VERBOSE = args.verbose
archives = list(args_get_archives(args))
if not archives:
print "ERROR: no archives specified. Specify an archive or a config file."
return 1
for a in archives:
print "Processing:", a["name"]
slack = Slacker(a["token"])
with SlackArchive(slack, a) as archive:
needs_upgrade = archive.needs_upgrade()
if needs_upgrade:
print "Notice: wayslack needs to fiddle around with some symlinks."
print "This will cause some non-destructive changes to the directory."
res = raw_input("Continue? Y/n: ")
if res and res.lower()[:1] != "y":
break
archive.upgrade()
if needs_upgrade or args.download_everything:
archive.download_all_files()
archive.refresh()
archive.delete_old_files(args.confirm_delete)
def __init__(self, config):
self.config = config
self.slack = Slacker(self.config.slackToken)
self.icon = SLACK_ICON
def connect(self):
self.client = Slacker(self.api_key)
self.update_channels()
#Set the appropriate settings for each alert
forms.py 文件源码
项目:slack-announcement-approval
作者: trianglefraternitymtu
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def __init__(self, *args, **kwargs):
super(TeamSettingsForm, self).__init__(*args, **kwargs)
slack = Slacker(kwargs['instance'].access_token)
priv_ch = [(g['id'], g['name']) for g in slack.groups.list().body['groups'] if not (g['is_archived'] or g['name'].startswith('mpdm'))]
pub_ch = [(c['id'], c['name']) for c in slack.channels.list().body['channels'] if not c['is_archived']]
users = [(u['id'], u['profile']['real_name']) for u in slack.users.list().body['members'] if not u['deleted']]
self.fields['post_channel'].widget = forms.Select(choices=tuple(pub_ch))
self.fields['approval_channel'].widget = forms.Select(choices=tuple(pub_ch + priv_ch + users))
def __init__(self):
super(Bot, self).__init__()
self.name = "pythonboardingbot"
self.emoji = ":robot_face:"
# When we instantiate a new bot object, we can access the app
# credentials we set earlier in our local development environment.
self.oauth = {"client_id": settings.SLACK_CLIENT_ID,
"client_secret": settings.SLACK_CLIENT_SECRET,
# Scopes provide and limit permissions to what our app
# can access. It's important to use the most restricted
# scope that your app will need.
"scope": "bot"}
self.verification = settings.SLACK_VERIFICATION_TOKEN
# NOTE: Python-slack requires a client connection to generate
# an oauth token. We can connect to the client without authenticating
# by passing an empty string as a token and then reinstantiating the
# client with a valid OAuth token once we have one.
self.client = SlackClient("")
self.slacker = Slacker("")
# We'll use this dictionary to store the state of each message object.
# In a production envrionment you'll likely want to store this more
# persistantly in a database.
self.messages = {}
self.authed_teams = {}
#self.last_messages = list()
def auth(self, code):
"""
Authenticate with OAuth and assign correct scopes.
Save a dictionary of authed team information in memory on the bot
object.
Parameters
----------
code : str
temporary authorization code sent by Slack to be exchanged for an
OAuth token
"""
# After the user has authorized this app for use in their Slack team,
# Slack returns a temporary authorization code that we'll exchange for
# an OAuth token using the oauth.access endpoint
auth_response = self.client.api_call(
"oauth.access",
client_id=self.oauth["client_id"],
client_secret=self.oauth["client_secret"],
code=code
)
# To keep track of authorized teams and their associated OAuth tokens,
# we will save the team ID and bot tokens to the global
# authed_teams object
team_id = auth_response["team_id"]
self.authed_teams[team_id] = {"bot_token":
auth_response["bot"]["bot_access_token"]}
# Then we'll reconnect to the Slack Client with the correct team's
# bot token
self.slacker = Slacker(self.authed_teams[team_id]["bot_token"])
team = self.find_team(team_id)
if team is None:
team = Team(team_id=team_id,
name=auth_response["team_name"],
bot_user_id=auth_response["bot"]["bot_user_id"],
bot_access_token=auth_response["bot"]["bot_access_token"])
team.save()
def find_team(self, team_id):
try:
team = Team.objects.get(team_id=team_id)
#self.client = SlackClient(team.bot_access_token)
self.slacker = Slacker(team.bot_access_token)
self.id = team.bot_user_id
except Team.DoesNotExist:
team = None
return team
def slacker():
""" Keep the slacker session short-lived, use 'with slacker() as slack'"""
slack = Slacker(os.environ['SLACK_API_TOKEN'])
yield slack
def slack_notify(text=None, channel='#test', username='???', attachments=None):
token = settings.SLACK_TOKEN
slack = Slacker(token)
slack.chat.post_message(text=text, channel=channel, username=username, attachments=attachments)
def __init__(self, token, verbose=False, request_pause_period=0.5):
self.slack = slacker.Slacker(token)
self.verbose = verbose
self.request_pause_period = 0.5
self._invite_link = None
def __init__(self, api_key, username, channel):
"""
:param api_key: string
:param username: string
:param channel: string
"""
self.username = username
self.channel = channel
self.slack = Slacker(api_key)
def auth_slack():
api = Slacker(bot_secret_)
try:
api.auth.test()
except Exception as e:
print('slack not authed\n', e)
return api