Twilio WhatsApp bug - python-3.x

I am getting this unexpected error with no explanation regarding Twilio API for WhatsApp messaging:-
print("Please enter a message.")
body_of_the_message = input()
account_sid = mysid
auth_token = myauthtoken
client = Client(account_sid, auth_token)
message = client.messages.create(from_='whatsapp:mytwilionum', body=(body_of_the_message),to='whatsapp:+myphone' )
sid = message.sid
print(f"The message SID is:- {sid}")
When I run this, I pass in “Hi there.” for the input.
This is what I get in response:-
The message SID is:- (sid)
I don’t see any notifications for the message being sent, and even when I check the chat history. Please help me with this stuff.

Related

telegram python - automation connect and send a message

trying to explore telegram python and create an automation that can send data, but for now I'am trying to connect my server with centOS to telegram during my testing I received an error when I run the python script, is there someone know what I need to check or modify to my script?
Error:
Request caused struct.error: required argument is not an integer: SendMessageRequest(peer=InputPeerUser(user_id='user_id', access_hash='user_hash'), message='Testing...', no_webpage=False, silent=None, background=None, clear_draft=False, reply_to_msg_id=None, random_id=57746331822001234, reply_markup=None, entities=[], schedule_date=None)
api_id = 'telegram app id'
api_hash = 'telegram hash'
token = 'telegram token'
message = "Testing..."
phone = '213phoneNumber'
client = TelegramClient('session', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code:'))
try:
receiver = InputPeerUser('user_id', 'user_hash')
client.send_message(receiver, message, parse_mode='html')
except Exception as e:
print(e);
client.disconnect()

Whatsapp bot using Twilio and Flask- Wait for Reply

I was building a WhatsApp bot using Twilio and Flask. So what should I do to make my WhatsApp bot wait for user reply and then execute the rest of the code. For example, my bot asks the user yes or no, the bot should wait for a reply, and based on the message received execute the rest of the code.
msg = request.form.get('Body')
resp = MessagingResponse()
msg = resp.message()
msg.body('Yes or No')
return str(resp)
{Wait For Reply}
if msg == 'yes':
do something
else:
do else
I am a begginer at Python.Please Help me .Thanks in advance

send message from bot to direct message after typing /slash command

I'm trying to make SlackBot and if I call him in some public channel it works fine but when I call him (type slash-command) in any direct channel I receive "The server responded with: {'ok': False, 'error': 'channel_not_found'}". In public channels where I've invited my bot it works fine, but if I type "/my-command" in any DM-channel I receive response in separate DM-channel with my bot. I expect to receive these responses in that DM-channel where I type the command.
Here is some part of my code:
if slack_command("/command"):
self.open_quick_actions_message(user_id, channel_id)
return Response(status=status.HTTP_200_OK)
def open_quick_actions_message(self, user, channel):
"""
Opens message with quick actions.
"""
slack_template = ActionsMessage()
message = slack_template.get_quick_actions_payload(user=user)
client.chat_postEphemeral(channel=channel, user=user, **message)
Here are my Event Eubscriptions
Here are my Bot Token Scopes
Can anybody help me to solve this?
I've already solved my problem. Maybe it will help someone in the future. I've sent my payload as the immediate response as it was shown in the docs and the response_type by default is set to ephemeral.
The part of my code looks like this now:
if slack_command("/command"):
res = self.slack_template.get_quick_actions_payload(user_id)
return Response(data=res, status=status.HTTP_200_OK)
else:
res = {"text": "Sorry, slash command didn't match. Please try again."}
return Response(data=res, status=status.HTTP_200_OK)
Also I have an action-button and there I need to receive some response too. For this I used the response_url, here are the docs, and the requests library.
Part of this code is here:
if action.get("action_id", None) == "personal_settings_action":
self.open_personal_settings_message(response_url)
def open_personal_settings_message(self, response_url):
"""
Opens message with personal settings.
"""
message = self.slack_template.get_personal_settings_payload()
response = requests.post(f"{response_url}", data=json.dumps(message))
try:
response.raise_for_status()
except Exception as e:
log.error(f"personal settings message error: {e}")
P. S. It was my first question and first answer on StackOverflow, so don't judge me harshly.

Trying to send emails with Gmail API

I've been followning tutorials and reading articles trying to learn how to make sense of the gmail API using python 3.
I've gotten stuck on the messages.send method.
My authentication works but my CreateMessage function is throwing an error.
Here is my code so far:
def CreateMessage(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_bytes())}
message = CreateMessage('xxxxxxxx#gmail.com','xxxxxxxx#gmail.com','subject','message text')
service = build('gmail', 'v1', credentials=creds)
created_message = service.users().messages().send(userId='me', body=message).execute()
The error it's throwing is "TypeError: Object of type bytes is not JSON serializable"
Any and all contrusctive criticism is welcome. Or any quality tutorials on the subject you can direct me to! Thank you.
base64.urlsafe_b64encode returns a bytes object. You should convert this to a string with .decode("utf-8"), which should fix your error.

Send messages to telegram group without user input

I'm trying to build a bot which automatically sends a message whenever there is an update in the latest news using python. Following is what I did.
companies = {
"name_1": {
"rss": "name_1 rss link",
"link": "name_1 link"
}
}
import feedparser as fp
import time, telebot
token = <TOKEN>
bot = telebot.TeleBot(token)
LIMIT = 1
while True:
def get_news():
count = 1
news = []
for company, value in companies.items():
count = 1
if 'rss' in value:
d = fp.parse(value['rss'])
for entry in d.entries:
if hasattr(entry, 'published'):
if count > LIMIT:
break
news.append(entry.link)
count = count + 1
return (news)
val = get_news()
time.sleep(10)
val2 = get_news()
try:
if val[0]!=val2[0]:
bot.send_message(chat_id= "Hardcoded chat_id", text=val2[0])
except Exception:
pass
How can I update my code so that the bot publishes the latest news to all the groups to which it is added?
I got the chat_id using:
bot.get_updates()[-1].message.chat.id
Any suggestions on how to automate this?
Using the python-telegram-bot api, you can send a message like this
bot.send_message(id, text='Message')
you need the "bot" and "id"
I keep these in a dictionary called "mybots" which I fill/update when people interact with the bot for the first time / or on later communication with the bot. It's possible to pickle this dictionary to keep it persistant.
mybots = {}
def start(bot, update):
"""Send a message when the command /start is issued."""
mybots[update.message.chat_id] = bot
update.message.reply_text('Hello{}!'.format(
update.effective_chat.first_name))
def send_later():
for id, bot in mybots.items():
bot.send_message(id, text='Beep!')
In short, you can use sendMessage() to send message to a specific group or user.
bot.sendMessage(chat_id=chat_id, text=msg)
the complete code,
import telegram
#token that can be generated talking with #BotFather on telegram
my_token = ''
def send(msg, chat_id, token=my_token):
"""
Send a message to a telegram user or group specified on chatId
chat_id must be a number!
"""
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id=chat_id, text=msg)

Resources