Lita.io Handler Plugin - How to get a list of all joined rooms - ruby

I am in the process of writing a Handler Plugin for lita.io. What I want to do is provide a HTTP POST endpoint and when it is called I want to publish some chat message to all rooms that Lita has joined.
I already succeeded with posting to a specific room that is identified as parameter in the HTTP call doing it like this:
def receive(request, response)
room = request.params['room']
Lita.logger.debug("stash-post-receive: room = #{room}")
target = Source.new(room: room)
json_data = parse_json(request.body.read) or return
message = format_message(json_data)
robot.send_message(target, message)
end
But this requires the caller to already supply which room to post to. Is there a way to retrieve a list of all rooms that Lita has joined so I can post there?

Currently there is not a generic way to do this. The adapter would have to expose an adapter-specific API for it.

Related

Slack API: select conversation members while filtering out bots without n+1

I need to select all members of a conversation who are not bots. It appears the way to do this is to first call conversations.members and then for each member call users.info. Using the slack ruby client, that boils down to this:
client = Slack::Web::Client.new(token: "MY-OAUTH-TOKEN")
# returns an array of user ids
response = client.conversations_members(channel: "#some-channel", limit: 500)
member_ids = response.members
members = member_ids.reject do |member_id|
# returns a https://api.slack.com/types/user object
user = client.users_info(user: member_id)
user["user"]["is_bot"] == true
end
This obviously presents an n+1 problem. I'm wondering if I've overlooked a better API method to call, or an API method argument that could help with this, whether via slack-ruby-client, or just via the vanilla API methods.
Unfortunately, Currently Slack does not have a single API call solution to your problem statement.

How to send DM specific user with id?

I want to make a bot that sends me DM, but it has error
It is my code:
member = client.get_user(int(my id))
await member.send('abc')
And error:
AttributeError: 'NoneType' object has no attribute 'send'
Make sure you replace '1234567890' with your own user ID
user = client.get_user(1234567890)
await user.send("Hi!", tts=True)
Example -
#client.command()
async def dm(ctx):
user = client.get_user(1234567890)
await user.send("Hi!", tts=True)
Before you do anything
First, make sure the bot is in some way connected to you, whether that be you share a guild or you already have a DM channel open with the bot. Second, make sure you allow DMs from shared server members or strangers so that the bot's DM won't be blocked.
Code
Instead of naming your variable "member", let's name it something more appropriate since you are retrieving a User object instead of a Member. Next, you want to test if you and the bot share a DM channel, if not the bot will create one, and then you can send the message.
user = client.get_user(int('0123456789'))
if not (dm_channel := user.dm_channel):
dm_channel = await user.create_dm()
await dm_channel.send('abc')

How to send to multiple recipients (WITHOUT LOOPING) while using variable alphanumeric sender ID?

I was wondering if there is a way to set multiple recipients WITHOUT looping over the list of recipients at my end?! Also most importantly while using variable alphanumeric sender ID and NOT buying a twilio number?
I can do all this for single recipient like this:
$twilio_client->messages->create(
'+64*******', //to
[
'from'=> 'foo',
'body' => 'bar'
]);
Works perfectly fine. However, doesnt work with multiple receivers.
Also note, it was bloody-1-step easy to implement smsbroadcast.com.au and pass all this in a simple call (simple call, quick fast, super easy documentation - unlike twilio which has like a billion lines of confusing documentation, 200 similar products and YET no direct api to check balance, or do a simple thing such as multiple recipients!!)
After a lot of back and through with the support, plus reading all the over-written-essay (so-called documentations), finally I found a way to get all that done.
[Step 1: Configuration]
You have to implement Notify product which is a separate product than the Message product.
So from left menu Notify> Service> add New. Here you need to add a Messaging Service and have it selected here for Notify.
On the Messaging Services page, it will ask you to buy a twilio number. Instead just click on Configure from the left menu and put in all the details you need.
Specifically and importantly, make sure you have Alpha Sender ID checked and a default Alpha Sender text entered there. This will be the default fallback in case if your api call fails to accept the from param.
.
[Step 2: API Call]
//$notify_service_SID = the SID from the Notify Service you added in step 1
$client = new Client($this->Account_SID, $this->auth_token);
$notify_obj = $client->notify->services($notify_service_SID);
//you need receivers in a JSON object such as the following, plus make sure numbers are starting with country code to ensure alpha sender works correctly
$receivers_json = [0=>'{"binding_type":"sms","address":"+614********"}']+[1=>'{"binding_type":"sms","address":"+614*******"}']
$call_ret = $notify_obj->notifications->create([
'toBinding'=> $receivers_json,
'body' => $msg, //actual message goes here
'sms' => [
'from'=> $sender //alphanumeric variable sender
],
]);
.
[Step 3: Check for errors]
There is no direct way to check all errors in twilio when implementing Notify. Here is my mixed approach.
Exception handling to the notifications->create call
$call_ret will have err if the Notify fails, but not when the Message fails. because Notify just passes the call to Message and there is no direct way to check Message errors over Notify call. So you would check for $call_ret['err']
Call the Alerts API; fetch all recent alerts, and match against the Notification SID you received from the last call.
--
Here is how to do the Alerts check:
$alerts = #$client->monitor->v1->alerts->read();
if(is_array($alerts))
foreach($alerts as $av)
{
$t = #$av->toArray();
#parse_str($t['alertText'], $alert_details);
if(isset($alert_details['notificationSid']) && $alert_details['notificationSid'] == $call_retx['sid'])
{
$alert_err = $alert_details['description'];
break;
}
}
$alert_err will carry an error if there was an error. Apart from this there is no direct way to do it. You can fetch these Alerts via crons or you can setup a webhook for them to do a call back. Or simply implement a one call simple api that does it all in super simple way such assmsbroadcast.

Using DocuSign API and Ruby

I am getting started with Docusign, and even with Ruby. I am trying to get my head wrapped around something and I need your help.
I am trying in Ruby to create a helper in order to prefill a contract with the information I posses such as the client's information etc. And have that sent to the 2 people who need the contract. I am a little stuck in the steps I need to take in order to get the communication working and grabbing the information I need.
Any help or tips is appreciated.
I have installed the gem for the docusign API, I have the docusign-ruby-client code, I have also created my template, got my integrator key. I am stuck with the next step. How do I actually use in my project all these things together in order to automatically fill in the template with the information from the client ? –
EDITS:
I am unsure on how to use this below in order to get my template, fill it automatically with my client info, and when done, send the pre-filled contract to 2 people.
host = 'https://demo.docusign.net/restapi'
integrator_key = 'e5fdb0cd-a206-4934-91f1-5d00000000'
user_id = 'myemail#gmail.com'
expires_in_seconds = 3600 #1 hour
auth_server = 'account-d.docusign.com'
private_key_filename = '[REQUIRED]'
# STEP 1: Initialize API Client
configuration = DocuSign_eSign::Configuration.new
configuration.host = host
api_client = DocuSign_eSign::ApiClient.new(configuration)
api_client.configure_jwt_authorization_flow(private_key_filename, auth_server, integrator_key, user_id, expires_in_seconds)
# STEP 2: Initialize Authentication API using the API Client
authentication_api = DocuSign_eSign::AuthenticationApi.new(api_client)
# STEP 3: Make the login call
login_options = DocuSign_eSign::LoginOptions.new
login_information = authentication_api.login(login_options)
if !login_information.nil?
login_information.login_accounts.each do |login_account|
if login_account.is_default == "true"
# STEP 4: Extract the user information
base_url = login_account.base_url
account_id = login_account.account_id
puts base_url
puts account_id
# IMPORTANT: Use the base url from the login account to update the api client which will be used in future api calls
base_uri = URI.parse(base_url)
api_client.config.host = "%s://%s/restapi" % [base_uri.scheme, base_uri.host]

could not send the SMS message via Tropo

We are using the TropoSharp to send SMS message to my phone. The weird part is that I didn't get any SMS message, rather I get a phone call and it is very short and I could not figure out what the person is talking over the phone.
By looking at the code, we could not figure out what's wrong:
string voiceToken = "xxx";
string messagingToken = "xxx";
IDictionary<string, string> parameters = new Dictionary<String, String>();
parameters.Add("sendToNumber", "xxx");
parameters.Add("sendFromNumber", "+1 201-xxx-04xx");
string channel = Channel.Text;
parameters.Add("channel", channel);
string network = Network.SMS;
parameters.Add("network", network);
parameters.Add("msg", HttpUtility.UrlEncode("This is a test message from C#."));
Tropo tropo = new Tropo();
XmlDocument doc = new XmlDocument();
string token = channel == Channel.Text ? messagingToken : voiceToken;
doc.Load(tropo.CreateSession(token, parameters));
Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper());
Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText);
Console.ReadKey();
Here is the http request (removed some sensitive information)
GET http://api.tropo.com/1.0/sessions?action=create&token=xxxxx&sendToNumber=xxx&sendFromNumber=+1%20201-xxx-xxxx&channel=TEXT&network=SMS&msg=This+is+a+test+message+from+C%23.& HTTP/1.1
Host: api.tropo.com
Connection: Keep-Alive
here is the response (I guess it only means that request is submitted successful):
<session><success>true</success><token>xxxx</token><id>5c994e73ab85ff47fd1af4ffd4002e00
Any idea where we did wrong here? Thanks
You're using the scripting approach, not WebAPI, right? Can you post the script that your application is using? It's my understanding that when you create a session, you're just passing variables up to your script. Your script might be completely ignoring those variables, and just making a voice call.
I agree about your last point. That response just tells you that it succeeded in creating the session. It doesn't return any additional information about other steps of the process.
There are two tokens for your application, one for voice and one for messaging. Are you using the one for messaging? Also, outbound messaging is not turned on be default for your application. You have to contact Tropo support to turn it on for development. They may require you to put some money in your account to do this, but they will not charge you unless you start abusing this feature during development.

Resources