How to find workspace name? - python

How do I find the workspace name from the message using Slack bot for Python? I can find username using the following:
username = message.channel._client.users[message.body['user']]['id']
But I don't know how to find the workspace name.

One approach is to call auth.test with the token of the respective team ID.
It will return the workspace name for the token / team ID in the team property.
Example output:
{
"ok": true,
"url": "https://subarachnoid.slack.com/",
"team": "Subarachnoid Workspace",
"user": "grace",
"team_id": "T12345678",
"user_id": "W12345678"
}
Example code for Python 3.6+ / slackClient 2.1:
import slack
client = slack.WebClient(token='YOUR_TOKEN')
response = client.auth_test()
print(response['team'])
Example code for Python < 3.6 / slackClient v1
from slackclient import SlackClient
response = self.sc.api_call('auth.test')
if not response['ok']:
raise RuntimeError("...")
else:
print response['team']

Actually I was experimenting with the above solution and decided to explore the dictionary that was returned with:
username = message.channel._client.users[message.body['user']]
It is possible to obtain team id much easier with Slack bot like this (the solution was in plain sight all along):
username = message.channel._client.users[message.body['user']]['team_id']
But thank you for your assistance, #Erik! :)

Related

How can I query UserId for AWS SSO Users using Boto3

How can I get UserId for AWS SSO Users using Boto3.
I wanted to use it to assign permissions to a user for a specific aws account using below code, however, this requires PrincipalId which is some 16-20 digit number associated with each user and is called User ID in the AWS console.
You can read about it - here
response = client.create_account_assignment(
InstanceArn='string',
TargetId='string',
TargetType='AWS_ACCOUNT',
PermissionSetArn='string',
PrincipalType='USER'|'GROUP',
PrincipalId='string'
)
If you have the UserName for the user you'd like to assign permissions for, you can programmatically use IAM to determine that user's UserId:
import boto3
# Get the UserId.
user_name = 'the user name here'
iam_client = boto3.client('iam')
result = iam_client.get_user(UserName=user_name)
user_id = result['User']['UserId']
# Assign permissions to the UserId.
sso_admin_client = boto3.client('sso-admin')
response = sso_admin_client.create_account_assignment(
InstanceArn='string',
TargetId='string',
TargetType='AWS_ACCOUNT',
PermissionSetArn='string',
PrincipalType='USER',
PrincipalId=user_id
)
You'll also need to use the 'identitystore' to get user or group IDs. Try this from the docs -
import boto3
client = boto3.client('identitystore')
response = client.get_user_id(
IdentityStoreId='string',
AlternateIdentifier={
'ExternalId': {
'Issuer': 'string',
'Id': 'string'
},
'UniqueAttribute': {
'AttributePath': 'string',
'AttributeValue': {...}|[...]|123|123.4|'string'|True|None
}
}
)
Although I personally found that the above method didn't work for me due to it not being available in my installed version of Boto3, so I did this instead which worked perfectly -
import boto3
client = boto3.client('identitystore')
response = client.list_users(
IdentityStoreId='string',
Filters=[
{
'AttributePath': 'UserName',
'AttributeValue': 'string'
},
]
)
print(response["Users"][0]["UserId"])
Sources:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#id24
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#IdentityStore.Client.get_user_id
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#IdentityStore.Client.list_users

Azure Python how to link child/related tickets to an already created ticket?

I am using the Azure Python tool to create Epic/Story/Feature work items in a python script like so:
# add fields
jpo = JsonPatchOperation()
jpo.from_ = None
jpo.op = "add"
jpo.path = "/fields/Microsoft.VSTS.Scheduling.FinishDate"
jpo.value = default_field
jpos.append(jpo)
#create work item
createdWorkItem = wit_client.create_work_item(
document=jpos,
project=project.id,
type="EPIC",
validate_only=validate_only,
bypass_rules=bypass_rules,
suppress_notifications=suppress_notifications
)
#save details to local json file
epic_details = {
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Hierarchy-Reverse",
"name": "Parent",
"url": createdWorkItem.url
}
}
I need to link my tickets together, such as adding a Child / Parent relationship between tickets. I'm trying to do this by creating all my tickets first, then linking them all where needed.
Is there some way with the Azure Devops Python tool that I can add a child workitem to a epic workitem if both tickets already exist? Thanks.
edit: I've found the function ParentChildWIMap referenced here:
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/work/models.py#L711
But I'm unsure on how to use it
If you use https://github.com/microsoft/azure-devops-python-api , you can try this sample:
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v6_0.py_pi_api import JsonPatchOperation
import pprint
# Fill in with your personal access token and org URL
personal_access_token = '<pat>'
organization_url = 'https://dev.azure.com/<org>'
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
# Get a client (the "core" client provides access to projects, teams, etc)
wi_client = connection.clients.get_work_item_tracking_client()
parent_id = 2129
child_id = 2217
parent_work_item = wi_client.get_work_item(parent_id);
pprint.pprint(parent_work_item.url)
patch_document = []
patch_document.append(JsonPatchOperation(op='add',path="/relations/-",value={"rel": "System.LinkTypes.Hierarchy-Reverse","url": parent_work_item.url}))
wi_client.update_work_item(patch_document, child_id)
Took me quite some time to figure this one out too.
Similar to the previous answer, an example on how to create work items with optional subtasks based on content from yaml files:
https://github.com/filipjonckers/azure-devops-bulk-workitems
Hope this is helpful.

Update a subscriber custom field using campaign monitor API and python

I've tried getting this to work every which way I can. I've poured through the campaign monitor API docs and search every possible article on the internet I could find. I didn't find one single example of code to update a subscriber record. I can get the record. I just can't update it and I am hoping someone can help me figure out what I am doing wrong. Thank you!
from createsend import *
def GetSubscribers(token, refresh_token, list_id):
auth = {
'access_token': token,
'refresh_token': refresh_token}
user_email = 'email#example.com'
subscriber = Subscriber(auth, list_id, user_email).get()
for i in subscriber.CustomFields:
for n in i.__dict__.keys():
print(i.__dict__[n])
if i.__dict__[n] == "campaign_code":
print(n, i.__dict__[n])
print(i.__dict__["Value"])
campaign_code = i.__dict__["Value"]
new_campaign_code = campaign_code + "_REPLIED"
print(new_campaign_code)
custom_fields = [
{"Key": i.__dict__[n], "Value": new_campaign_code}]
Subscriber.update(user_email, "Subscriber",
custom_fields, True, True, "Yes")
params = {"email": self.email_address}
AttributeError: 'str' object has no attribute 'email_address'
I figured it out. This is the correct structure to update a subscriber using the createsend python wrapper:
custom_fields = [{"Key": key, "Value": value}]
subscriber = Subscriber(auth, list_id, user_email).update(
new_user_email, "Subscriber", custom_fields, True, "Yes")
This one took a lot of time for me to figure out. I hope this post will help save some time for anyone trying to update subscribers in campaign monitor.

Microsoft Teams Python Botbuilder Proactive Messaging

What was simple in Webex now seems fairly complicated in the Microsoft world.
What I specifically am looking to do is:
Create a bot in the Azure Bot Framework (Done)
Identify recipient ids using the botbuilder sdk using the recipient email
Use Botframework-Connector to individually identify these recipients, create new conversations, and proactively message them
This is what I have been using so far
https://pypi.org/project/botframework-connector/
from botbuilder.schema import *
from botframework.connector import ConnectorClient
from botframework.connector.auth import MicrosoftAppCredentials
APP_ID = 'azure_bot_app_id'
APP_PASSWORD = 'azure_bot_app_password'
SERVICE_URL = 'azure_bot_messaging_endpoint'
CHANNEL_ID = 'msteams'
BOT_ID = 'azure_bot_subscription_id'
RECIPIENT_ID = 'msteams_individual_user_id'
credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
connector = ConnectorClient(credentials, base_url=SERVICE_URL)
conversation = connector.conversations.create_conversation(ConversationParameters(
bot=ChannelAccount(id=BOT_ID),
members=[ChannelAccount(id=RECIPIENT_ID)]))
connector.conversations.send_to_conversation(conversation.id, Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text='Hello Person!'))
Is this even close to the right approach?
This was the easiest way I found to make it work.
from config import DefaultConfig
from botframework.connector.connector_client import ConnectorClient
from botframework.connector.models import ConversationParameters
from botframework.connector.auth.microsoft_app_credentials import MicrosoftAppCredentials
from botbuilder.core import MessageFactory
from botbuilder.schema import ChannelAccount
CONFIG = DefaultConfig()
recipient_id = <<RECIPIENT_ID>>
to = ChannelAccount(id=recipient_id)
bot_channel = ChannelAccount(id='msteams')
MicrosoftAppCredentials.trust_service_url(CONFIG.SERVICE_URL)
credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
conn_client = ConnectorClient(credentials, CONFIG.SERVICE_URL)
message_activity = MessageFactory.text(f"Personal message from the Bot!");
conversation_params = ConversationParameters(members=[to], channel_data={ 'tenant': { 'id': CONFIG.TENANT_ID } })
conversation = conn_client.conversations.create_conversation(conversation_params)
conn_client.conversations.send_to_conversation(conversation.id, message_activity)
It is easy to infer all the uppercase variables.
The <<RECIPIENT_ID>> is the MS Teams ID of the user you want to send the message.
Hope this helps.
MSFT does not provide good examples in Python.
With a cursory glance it looks ok (I don't work in Python so can't actually run the example). One thing that does look missing in the TrustServiceUrl call. See here for details.

PRAW: Authorizing with OAuth prevents me from getting submissions/comments

If I use OAuth, I am unable to get new submissions or comments from a subreddit.
My Oauth code looks like this:
import praw
import webbrowser
r = praw.Reddit(user_agent)
r.set_oauth_app_info(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
authURL = r.get_authorize_url("FUZZYPICKLES", "identity submit", True)
webbrowser.open(authURL)
authCode = input("Enter the code: ")
accInfo = r.get_access_information(authCode)
After that I can try to get submissions
submission = r.get_subreddit("test").get_new()
or comments
comments = r.get_comments("test")
but if I use either value, the program crashes with the error:
raise OAuthInsufficientScope('insufficient_scope', response.url)
praw.errors.OAuthInsufficientScope: insufficient_scope on url https://oauth.reddit.com/r/test/comments/.json
If I don't use OAuth, either by using login() or by just not authorizing, I have no such issues. I am using Python 3.4. What am I doing wrong?
I found the solution myself. To read posts, you need "read" in your list of requested scopes. So, "identity submit" should be "identity read submit".

Categories