Creating and sending vCard files via MMS - python

I'm trying to send vCard files (which allow you to save contacts on mobile devices) using Twilio's API and vobject.
Here's my code:
import vobject
import requests
from twilio.rest import Client
account_sid = 'MY_SID_HIDDEN'
auth_token = 'AUTH_TOKEN_HIDDEN'
j = vobject.vCard()
j.add('n')
j.n.value = vobject.vcard.Name(family='Harris', given='Jeffrey')
j.add('fn')
j.fn.value = 'Jeffrey Harris'
j.add('email')
j.email.value = 'jeffrey#osafoundation.org'
j.email.type_param = 'Internet'
client = Client(account_sid, auth_token)
client.api.account.messages.create(
to="NUMBER_HIDDEN",
from_="NUMBER_HIDDEN",
body=j
)
When my device receives the message, it looks like this:
<VCARD| [<EMAIL{'TYPE': ['Internet']}jeffrey#osafoundation.org>, <FN{}Jeffrey Harris>, <N{} Jeffrey  Harris >]>
Why is this happening?

I understand what you want to do, but there are a couple issues.
Vcards are files; you have put marked up text in a text field (body).
For attaching files using the API, you point it at a URL that the Twilio Server can access and make sure you properly declare your mime-type encoding in the API and on server where the card will be stored.
Note: I'm not sure if the mime-type is required anymore, as they don't use it on this example for a attaching picture (https://www.twilio.com/docs/api/messaging/send-messages#send-a-message-with-an-image-url ; change the language to python).
You would attach the file (vcard) using mediaUrl.
ex// mediaUrl=https://qrstuff.com/vcard.download/dec91a6d6/yo_yo_ma_vCard.vcf

Related

How to Send a URL Link within the Text Body with the Twilio API using Python

I am trying to send a text message that contains both text and a hypeprlink but am encountering the following message from the Twilio API:
"Error - 12300 Invalid Content-Type: Attempt to retrieve MediaUrl returned an unsupported Content-Type."
Here is the code I am attempting to leverage:
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body='Article: https://4r7s.short.gy/GPaoh7',
from_='123-345-5667',
to='123-345-5668',
)
When I send a message without a hyperlink it works fine (e.g. body = 'Here is the article for you to read') but when it contains a link I receive the aforementioned error. I've also tried using a shortened url of the above but that causes the same issue.
I was just able to send messages containing that exact link using my own Twilio account.
There might be an issue in that you are using phone numbers in local format, when they should be provided in e.164 format.
It's possible that your message is being blocked. Certain carriers don't like when you use link shorteners to obscure a link.
The error you are getting definitely seems weird, since you are not sending media. If you continue to have issues with this, I would contact Twilio support.

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.

Receive and Print a Twilio SMS with Python

For clarification, I don't want to reply to the SMS. Every tutorial or document I've looked at is about setting up a port to listen on.
What I'm trying to do is just get the SMS and print it. I can send them fine and without problems.
Here is my sending function, and it works.
def send():
message = client.messages \
.create(
body=sendMSG,
from_='MY_TWILIO_NUMBER',
to='MY_PERSONAL_NUMBER'
)
print(message.sid)
How would you receive an SMS without Flask? Is there a way to do something similar to this method below just for receiving?
def receive():
message = client.messages \
.recieve(
from_='MY_PERSONAL_NUMBER',
to='MY_TWILIO_NUMBER'
)
print(message.sid)
I have not personally tried to get SMS messages from the logs before, always getting it directly through a webhook, but from what I see, it appears the command you might be looking for is list(). You can add filters, as shown in the API docs, and there are three filtering options. You can filter by DateSent, To, or From.
I have not tried this, but it would seem that the way to use this would be the following (adjusted from the code they supply):
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
messages = client.messages.list(from='MY_PERSONAL_NUMBER', to='MY_TWILIO_NUMBER')
for record in messages:
print(record.sid)
If that doesn't work, the variables they use are actually capitalized "To" and "From", so you might try that.
After looking at that a bit, you might be looking more for this:
received = client.messages.list(to='MY_TWILIO_NUMBER')
sent = client.messages.list(from='MY_PERSONAL_NUMBER')
That will separate out those sent to you, and those sent from you

Using Slack RTM API with Django 2.0

I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API.
I have a coded a program in python that performs the OAuth authentication process like so :
def initialize():
url="https://slack.com/api/rtm.connect"
payload={"token":"xxx"}
r=requests.post(url,payload)
res=json.loads(r.text)
url1=res['url']
ws = create_connection(url1)
return ws
My Requirement:
The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database.
As a stand alone python program I am receiving the stream of events from my channel.
My questions:
How do I successfully integrate this code to Django so that I can
fulfill my requirement?
Do I put the code in templates/views? What is the
recommended method to process this stream of data?
def initialize():
url = "https://slack.com/api/rtm.connect"
r = requests.get(url, params={'token': '<YOUR TOKEN>'})
res = r.json()
url1=res['url']
ws = create_connection(url1) #Note: There is no function called create_connnection() so it will raise an error
return ws
if you read the API web methods, you see :
Preferred HTTP method: GET
See here: Slack rtm.connect method
look at the comment, and thats the right code, see the differences between this code and yours.
basically to get JSON from a request don't use json.loads because this search your local computer not the request
use r.json() so it call the json you got from r.
Note that r.text will return raw text output so when you want to get url it will not be identified, with r.json you can call the object url as stated about
Hope this help.
and please could you tell us more what you wanna do with this in view ? because template is a directory which contains all the HTML files which you don't need to work with.
but why views.py ?

Telegram Bot API - Upload document with filename

How is it possible to send a document in telegram in python with an other filename that "document"?
I'm using the Python3. "doc" is a clear text i want to send as txt file.
url = baseurl + token + '/sendDocument'
dict = {'chat_id':chat_id}
r = requests.post(url, params=dict, files={'document':doc})
The received file is named "document", without a file extension. When I rewrite the files to
files={'document.txt':doc}
the Telegram replies
{"ok":false,"error_code":400,"description":"Bad Request: there is no document in the request"}
Does anyone know how to set a file name for the file?
According to the API page, you cannot do that. You must use predefined names for such types of API methods (document, photo, audio, etc.).
And even if you could - you won't be able to use your custom name to find your files because Telegram bot API uses its own file_id identifier for this purpose.
As a workaround you may store file_id—your_custom_document.txt relation on your backend and use file_id to communicate with Telegram servers.

Categories