Configuring errbot presence in HipChat - python

I'm trying to use Errbot with HipChat server (not cloud). It looks like Errbot is confused between a room name and its xmpp jid. For example, testing with room named BotTest that has jid of 1_bottest#conf.btf.hipchat.com:
When I set CHATROOM_PRESENCE to the room name and send any message in that room, Errbot crashes with the error "Room '1_bottest#conf.btf.hipchat.com' not found".
When I set it instead to the room's jid, Errbot creates a new room with the same name as the jid, and a jid of '1_1_bottestconf.btf.hipchat.com#conf.btf.hipchat.com'. Then when I send a message in that new room it crashes with the error "Room '1_1_bottestconf.btf.hipchat.com#conf.btf.hipchat.com' not found".
My config.py is below:
import logging
BACKEND = 'XMPP' # defaults to XMPP
BOT_DATA_DIR = r'/auto/home.nas03/eeshel/work/errbot/data'
BOT_EXTRA_PLUGIN_DIR = '/auto/home.nas03/eeshel/work/errbot/plugins'
BOT_LOG_FILE = r'/auto/home.nas03/eeshel/work/errbot/errbot.log'
BOT_LOG_LEVEL = logging.DEBUG
TEXT_COLOR_THEME = 'dark'
BOT_ADMINS = ('1_8#chat.btf.hipchat.com', )
BOT_PREFIX = '\\'
BOT_ALT_PREFIXES = ('Hermes',)
BOT_ALT_PREFIX_SEPARATORS = (':', ',', ';')
BOT_ALT_PREFIX_CASEINSENSITIVE = True
CHATROOM_FN = 'Hermes the Bot'
CHATROOM_PRESENCE = ('1_bottest#conf.btf.hipchat.com',)
BOT_IDENTITY = {
'username' : '1_2#hipchat.eng.<ourdomain>',
'password' : '*****',
'token' : '*****',
'endpoint' : '10.18.0.185',
}
XMPP_KEEPALIVE_INTERVAL = 60
XMPP_USE_IPV6 = False
XMPP_CA_CERT_FILE = "/etc/ssl/certs/ca-bundle.crt"

You can refer below link ,which will help you http://errbot.io/en/latest/user_guide/configuration/hipchat.html

While the documentation is very good, I also struggled to get these things just right. Once I did, a re-read of the doc makes sense, but hindsight is 20/20!
Here is an example config section to have your errbot connect to Hipchat:
# Assuming you are #jdoe in your Hipchat and you want admin privs for your bot
BOT_ADMINS = ('#jdoe', '#mmouse', )
# Let's assume your bot's Hipchat account is "superbot" with
# full name of "Super Bot"
BACKEND = 'Hipchat'
if BACKEND == 'Hipchat':
# http://errbot.io/en/latest/user_guide/configuration/hipchat.html
BOT_IDENTITY = {
# You get username by logging into Hipchat with the account, then go to
# Profile / XMPP/Jabber Info and find the "Jabber ID"
'username': '123456_1234567#chat.hipchat.com',
# Simply the password of the Hipchat account
'password': 'password12345',
# You get token by logging into Hipchat with the account, then go to
# Profile / API Access and generate an API token--assigning it all
# scopes unless you know otherwise.
'token': 'azwx2BdVzGz0riEjqybWinLbUkBSIz6rpsa259HE',
## If you're using HipChat server (self-hosted HipChat) then you should set
## the endpoint below. If you don't use HipChat server but use the hosted version
## of HipChat then you may leave this commented out.
#'endpoint': 'https://api.hipchat.com'
}
CHATROOM_FN = 'Super Bot'
BOT_ALT_PREFIXES = ('#superbot', '#SuperBot', '#stinkfinger',)
# To "listen" for any mentions of #superbot:
CHATROOM_PRESENCE = ()
# To also join rooms to listen to all messages in those rooms,
# do this instead:
#CHATROOM_PRESENCE = ('Room 1', 'Lounge',)
IMPORTANT also to note that I had to downgrade these packages to get Hipchat integration working. I made these changes in my requirements.txt:
pyasn1==0.3.7
pyasn1-modules==0.1.5
sleekxmpp==1.3.2

Related

How to send email notification using Cloud Pubsub

How to send email notification from Pub sub using python script when files are uploaded in google cloud compute engine.
The following examples illustrate the creation of notification channels with Python
def restore(project_name, backup_filename):
print(
"Loading alert policies and notification channels from {}.".format(
backup_filename
)
)
record = json.load(open(backup_filename, "rt"))
is_same_project = project_name == record["project_name"]
# Convert dicts to AlertPolicies.
policies_json = [json.dumps(policy) for policy in record["policies"]]
policies = [
monitoring_v3.AlertPolicy.from_json(policy_json)
for policy_json in policies_json
]
# Convert dicts to NotificationChannels
channels_json = [json.dumps(channel) for channel in record["channels"]]
channels = [
monitoring_v3.NotificationChannel.from_json(channel_json)
for channel_json in channels_json
]
# Restore the channels.
channel_client = monitoring_v3.NotificationChannelServiceClient()
channel_name_map = {}
for channel in channels:
updated = False
print("Updating channel", channel.display_name)
# This field is immutable and it is illegal to specify a
# non-default value (UNVERIFIED or VERIFIED) in the
# Create() or Update() operations.
channel.verification_status = (
monitoring_v3.NotificationChannel.VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED
)
if is_same_project:
try:
channel_client.update_notification_channel(notification_channel=channel)
updated = True
except google.api_core.exceptions.NotFound:
pass # The channel was deleted. Create it below.
if not updated:
# The channel no longer exists. Recreate it.
old_name = channel.name
del channel.name
new_channel = channel_client.create_notification_channel(
name=project_name, notification_channel=channel
)
channel_name_map[old_name] = new_channel.name
# Restore the alerts
alert_client = monitoring_v3.AlertPolicyServiceClient()
for policy in policies:
print("Updating policy", policy.display_name)
# These two fields cannot be set directly, so clear them.
del policy.creation_record
del policy.mutation_record
# Update old channel names with new channel names.
for i, channel in enumerate(policy.notification_channels):
new_channel = channel_name_map.get(channel)
if new_channel:
policy.notification_channels[i] = new_channel
updated = False
if is_same_project:
try:
alert_client.update_alert_policy(alert_policy=policy)
updated = True
except google.api_core.exceptions.NotFound:
pass # The policy was deleted. Create it below.
except google.api_core.exceptions.InvalidArgument:
# Annoying that API throws InvalidArgument when the policy
# does not exist. Seems like it should throw NotFound.
pass # The policy was deleted. Create it below.
if not updated:
# The policy no longer exists. Recreate it.
old_name = policy.name
del policy.name
for condition in policy.conditions:
del condition.name
policy = alert_client.create_alert_policy(
name=project_name, alert_policy=policy
)
print("Updated", policy.name)
For more information I recommend you read the following documentation about Managing notification channels by API
This product or feature is covered by the Pre-GA Offerings Terms of the Google Cloud Terms of Service. Pre-GA products and features might have limited support, and changes to pre-GA products and features might not be compatible with other pre-GA versions. For more information, see the launch stage descriptions.
Additionally You want to check this information about Setting up a messaging app this describes how to use Pub/Sub and Cloud Functions to enable near real-time notifications for SendGrid Email API, Slack, and WebEx Teams

How to work with slackbot in python?

I am trying to build a slackbot for my group , I tried sample codes and some other things but its not sending message to the group.
first i tried via terminal
export SLACK_API_TOKEN="my_token_id"
Then
from slackclient import SlackClient
import os
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
sc.api_call(
"chat.postMessage",
channel="#random",
text="Hello from Python! :tada:",
thread_ts="283.5127(dummy_id)",
reply_broadcast=False
)
print(sc)
#<slackclient.client.SlackClient object at 0x109b77ba8>
But there is no message in slack group.
I tried with this code:
from slackclient import SlackClient
import os
slack_token = os.environ['SLACK_API_TOKEN']
sc = SlackClient(slack_token)
print(sc.api_call("channels.list"))
its retuning :
{'error': 'invalid_auth', 'ok': False}
I am not getting what i am doing wrong , Access token is correct , i want to post some messages via a bot , so how i can create a bot on slack and using that bot i can send messages via python ?
I had similar issues when I implemented a slack bot with php & symfony.
It's not that simple to create and configure the slack app, bot and OAuth permissions properly.
I explained all these configurations in this blog post if you need it: https://blog.eleven-labs.com/en/en/replace-erp-by-slack-bot-with-dialogflow-and-symfony/
Also my code in PHP is very similar to what you need to parse Slack requests and post to its API.
Summary, TL;DR:
Go to https://api.slack.com/apps and click on 'Create New App'.
In this app configuration, go to the left menu 'Bot Users' or from 'Basic Information' > 'Add features and functionality' > 'Bots'.
Still in this app config, go to the menu 'OAuth & Permissions' and allow the scope 'chat:write:bot' and copy the value of 'OAuth Access Token'
From your code, call 'chat.postMessage' API method with an 'Authorization' header using previous token value.
built this from some examples found on the web: liza daly - brobot : github.com
and
How to Build Your First Slack Bot with Python : fullstackpython.com
certainly not the best implementation but it functions as an appropriate answer to (i think)
import random
import time
import re
from slackclient import SlackClient
bot_id = None
slack_token = 'xoxb-no.more.mister.nice.gui'
sc = SlackClient(slack_token)
# constants
RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
DEFAULT_RESPONSE = "greetings: 'hello', 'hi', 'greetings', 'sup', 'what's up' / commands: 'do'"
DEFAULT_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
:param slack_events:
:return:
"""
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 == bot_id:
return message, event["channel"]
return None, None
def parse_direct_mention(message_text):
"""
finds direct message and returns user id
:param message_text:
:return:
"""
matches = re.search(MENTION_REGEX, message_text)
# the first group contains the user name, the second group contains
# the remaining message
return (matches.group(1), matches.group(2).strip()) if matches else (None, None)
def handle_command(command, channel):
"""
executes bot command if the command is known
:param command:
:param channel:
:return:
"""
GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up",)
GREETING_RESPONSES = ["'sup brah", "hey", "*headnod*", "didjageddathingahsencha?"]
# default response is help text for the user
default_response = "Not sure what you mean. Try *{}*.".format(DEFAULT_RESPONSE)
# finds and executes the given command, filling the response
response = None
#implement more commands below this line
if command in GREETING_KEYWORDS:
response = random.choice(GREETING_RESPONSES)
else:
if command.startswith(DEFAULT_COMMAND):
response = "Sure...write some more code and I'll do that"
# Sends the response back to the channel
sc.api_call(
"chat.postMessage",
channel="#the_danger_room",
as_user="true:",
text=response or default_response)
if __name__ == "__main__":
if sc.rtm_connect(with_team_state=False):
print("Connected and running!")
#call web api method auth.test to get bot usre id
bot_id = sc.api_call("auth.test")["user_id"]
while True:
command, channel = parse_bot_commands(sc.rtm_read())
if command:
handle_command(command, channel)
time.sleep(RTM_READ_DELAY)
else:
print("Connection failed. Exception traceback printed above.")

In LDAP need roledn for Password Modify Extended Operation to allow users to change their own passwords

The issue I have is in the role(s) and/or access on the LDAP server. I added the Password Modify Extended Operation - ACI to our Sun Directory Server (Version 7.0) a while ago and the roledn specified (cn=Password Managers,...) is clearly not right. I need to specify the role so that a user can change their own password only. What role would allow that? How do I specify it?
The server is Solaris 10. I am including the information on the OID below and below that the python program that I am trying to use and the result from that program.
I borrowed heavily from the code in this post here on stack.
In my LDAP Server I find:
Properties of the selected Access Control Instruction
Required Field ACI Syntax:
(targetattr != "aci")(version 3.0; acl "Password Modify Extended Operation ";
allow( read, search, compare, proxy )
(roledn = " ldap:///cn=Password Managers,dc=example,dc=com" and authmethod = "SSL");)
Entry where the ACI is located:
oid=1.3.6.1.4.1.4203.1.11.1,cn=features,cn=config
I am working on a python 3.5 program to change user passwords. Here is the code so far:
import ldap3
import ssl
SERVER='ds2.example.com'
BASEDN = 'dc=channing,dc=example,dc=com'
USER = 'saltz'
SEARCHFILTER = '(uid=' + USER + ')'
CURRENTPWD="something"
NEWPWD="somethingelse"
user='uid=saltz,ou=People,dc=channing,dc=example,dc=com'
ldap_server = ldap3.Server(SERVER, port = 636, use_ssl = True,
get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, user, CURRENTPWD, auto_bind=True)
modify = ldap3.extend.standard.modifyPassword.ModifyPassword(conn,
user, NEWPWD, CURRENTPWD, controls=None)
resp = modify.send()
print(modify.result)
This is the result I got when I ran the above code:
{'result': 50, 'description': 'insufficientAccessRights', 'dn': '',
'message': 'Access to feature "oid=1.3.6.1.4.1.4203.1.11.1,cn=features,cn=config" denied.',
'referrals': None, 'responseName': None, 'responseValue': None,
'type': 'extendedResp', 'new_password': None}
Thanks for your help.

Passing a Facebook Oauth2 object while using Tornado

I am trying to implement oauth manually on my website which is being implemented using tornado. My url (localhost/form) contains a button which when clicked brings up a facebook login and then if the login is successful redirects back to the same site with a token (localhost/form?code=XXX) where I collect the token/code and begins taking requests from facebook.
My issue is that upon redirecting back to localhost/form with a given code, it appears that I reinitialize a brand new oauth2session object which does not match up with the token and I receive a GET request error. How should I correctly pass this oauth2session object or correctly reinitialize it? Is this reinitialization causing my error or something else? My current code which does not work is:
class FormHandler (BaseHandler):
def get(self):
client_id =XXX
client_secret =XXX
authorization_base_url = 'https://www.facebook.com/dialog/oauth'
token_url = 'https://graph.facebook.com/oauth/access_token'
facebook = OAuth2Session(client_id, redirect_uri='http://localhost/form')
facebook = facebook_compliance_fix(facebook)
authorization_url, state = facebook.authorization_url(authorization_base_url)
self.write('<button id="FacebookManual" type="button">Facebook Manual</button><br><script> document.getElementById("FacebookManual").onclick = function () {location.href ="'+authorization_url+'";};</script>')
#Check to see if I get redirected with a code
authorization_code=self.get_argument("code", default=None, strip=False)
if authorization_code is not None:
redirect_response='https://localhost/form/?code='+authorization_code
facebook.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response)
r = facebook.get('https://graph.facebook.com/me?')
self.write('Hello'+r.content)
#Roughly how my tornado is set up
def make_app():
return Application(
[
url('/', BaseHandler, { "var":"nothing" }, name="root"), # this is for the root! :)
url('/form', FormHandler, { "var":"initialize this!" }, name = "forlorn"),
],
# settings:
debug = True,
)
Edit: A friend advised me to include the error that I was receiving. The error that I get is a oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning! State not equal in request and response.
ERROR:tornado.access:500 GET /form?code=XxX

Retrieve message properties from Azure Service bus topics withn Python

Using Python 2.7 I need to get the properties of the message. I know the message contains 3 properties: cdId, active and alarm:
In C# I have this client which sends the message;
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
TopicClient newClient = TopicClient.CreateFromConnectionString(connectionString, "cdMessages");
var serviceMsg = new BrokeredMessage("Alarm Deactive");
serviceMsg.Properties["cdId"] = message.Properties["cdId"];
serviceMsg.Properties["active"] = false;
serviceMsg.Properties["alarm"] = false;
newClient.Send(serviceMsg);
I have made a subscription and I am able to receive the messages using python but I have no clue how to get the properties of the message.
key_name = '******'
key_value ='******'
service_namespace1 = '******'
sbs = ServiceBusService(service_namespace=service_namespace1,
shared_access_key_name=key_name,
shared_access_key_value=key_value)
Active = "active"
Deactive = "Deactivate"
sbs.create_subscription('cdmessages', 'AllMessages')
while True:
msg = sbs.receive_subscription_message('cdmessages', 'AllMessages', peek_lock=False)
print(msg.body)
MessageString = str(msg.body)
if MessageString.find(Active) == True
newState = "Activated"
return(newState)
I can get the "activated" part working because I send "Alarm Deactive" or "Alarm Active" as the message text but the is just hack I made to get it at least working partially. I need to be able to read the properties. I have tried msg.properties but that returns with an error that the properties attribute doesn't exists.
In the v7 of the azure-servicebus, you can utilize the application_properties.
https://learn.microsoft.com/en-us/python/api/azure-servicebus/azure.servicebus.servicebusmessage?view=azure-python

Categories