def add_slack_btn(request):
code = request.GET.get("code", "")
if len(code) < 8:
return HttpResponseBadRequest()
result = requests.post("https://slack.com/api/oauth.access", {
"client_id": settings.SLACK_CLIENT_ID,
"client_secret": settings.SLACK_CLIENT_SECRET,
"code": code
})
doc = result.json()
if doc.get("ok"):
channel = Channel()
channel.user = request.team.user
channel.kind = "slack"
channel.value = result.text
channel.save()
channel.assign_all_checks()
messages.success(request, "The Slack integration has been added!")
else:
s = doc.get("error")
messages.warning(request, "Error message from slack: %s" % s)
return redirect("hc-channels")
python类SLACK_CLIENT_ID的实例源码
def slack_oauth(request):
code = request.GET['code']
params = {
'code': code,
'client_id': settings.SLACK_CLIENT_ID,
"client_secret": settings.SLACK_CLIENT_SECRET
}
url = 'https://slack.com/api/oauth.access'
json_response = requests.get(url, params)
data = json.loads(json_response.text)
Team.objects.get_or_create(
name=data['team_name'],
team_id=data['team_id'],
bot_user_id=data['bot']['bot_user_id'],
bot_access_token=data['bot']['bot_access_token']
)
return HttpResponse('Bot added to your Slack team!')
def dispatch(self, request, *args, **kwargs):
try:
code = request.GET.get('code', '')
sc = SlackClient("")
result = sc.api_call("oauth.access", client_id=settings.SLACK_CLIENT_ID,
client_secret=settings.SLACK_CLIENT_SECRET, code=code,
redirect_uri=request.build_absolute_uri(reverse('oauth')))
if SlackAuth.objects.filter(team_id=result["team_id"]).exists():
SlackAuth.objects.get(team_id=result["team_id"]).delete()
slack_auth = SlackAuth.objects.create(access_token=result["access_token"], team_id=result["team_id"],
team_name=result["team_name"], bot_id=result["bot"]["bot_user_id"],
bot_access_token=result["bot"]["bot_access_token"])
retrieve_channel_users.delay(slack_auth.pk)
return HttpResponseRedirect(reverse("success"))
except Exception:
logger.error(traceback.format_exc())
return HttpResponseRedirect(reverse("failure"))
def slack_oauth(request):
code = request.GET['code']
params = {
'code': code,
'client_id': settings.SLACK_CLIENT_ID,
"client_secret": settings.SLACK_CLIENT_SECRET
}
url = 'https://slack.com/api/oauth.access'
json_response = requests.get(url, params)
data = json.loads(json_response.text)
Team.objects.get_or_create(
name=data['team_name'],
team_id=data['team_id'],
bot_user_id=data['bot']['bot_user_id'],
bot_access_token=data['bot']['bot_access_token']
)
return HttpResponse('Bot added to your Slack team!')
def add_slack(request):
if not settings.SLACK_CLIENT_ID and not request.user.is_authenticated:
return redirect("hc-login")
ctx = {
"page": "channels",
"slack_client_id": settings.SLACK_CLIENT_ID
}
return render(request, "integrations/add_slack.html", ctx)
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 authorize(request):
if request.session['authorize_state'] != request.GET['state']:
return render(request, "account/authorize_fail.html", {
"error": "Invalid state token.",
})
response = requests.post('https://slack.com/api/oauth.access', data={
'client_id': settings.SLACK_CLIENT_ID,
'client_secret': settings.SLACK_CLIENT_SECRET,
'code': request.GET['code'],
'redirect_uri': request.session['authorize_request_uri'],
})
data = response.json()
account, created = SlackAccount.objects.update_or_create(
user=request.user, team_id=data['team_id'], defaults={
'access_token': data['access_token'],
'scope': data['scope'],
'team_name': data['team_name'],
'incoming_webhook_url': data['incoming_webhook']['url'],
'incoming_webhook_channel': data['incoming_webhook']['channel'],
'incoming_webhook_configuration_url': (
data['incoming_webhook']['configuration_url']),
'bot_user_id': data['bot']['bot_user_id'],
'bot_access_token': data['bot']['bot_access_token'],
}
)
messages.success(request, "Heatherr is now linked to %s." % (
account.team_name,))
return redirect(reverse('accounts:profile'))
def get_slack_oauth_uri(request):
# scope = "bot+channels:write"
scope = "bot"
return "https://slack.com/oauth/authorize?scope=" + scope + "&client_id=" + settings.SLACK_CLIENT_ID + \
"&redirect_uri=" + request.build_absolute_uri(reverse("oauth"))
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()