I want to alert everyone on Slack App, which I can do manually by sending #here in the channel.
But I want to send it using my bot.
So, I tried this:
import numpy as np
import requests
data = {
'token': token,
'channel': channel,
'as_user': True,
'text': "<#here>"
}
requests.post(url='https://slack.com/api/chat.postMessage', data=data)
But it send just a usual message, not an alert message.
How can I send an alert message using my bot?
Related
Im learning how to set a twilio studio flow with python, I'm currently testing one of the templates that Twilio provides, and Im communicating with the bot from WhatsApp. However, I can only send the first message of the flow and if I send another message, this message pop up:
Unable to create record: Execution XXXXXXXXXXXXXXXXXXXXX is already active for this contact. End the active Execution before creating a new one
I tried to add .update(status='ended') to my variable, but it just kinda looped every time I sent a message, I know that every time that theres an incoming message it will trigger the conversation. So my question is, how can I continue the conversation flow without creating a new trigger every time that theres an incomming message?
Here's my flow in case it's necessary.
And this is the functions and endpoints that I'm using to trigger the action:
# twilio.route('/incoming_message', methods=['GET', 'POST'])
def incoming_message_data() -> str:
if request.method == 'POST':
response = {}
error, message, code = False, '', ''
message = incoming_message()
response.update({'sucess': True, 'message': message, 'message': f'{message}', 'status_code': 200, 'error': None, 'code': f'{code}'} if message and message != [{}]else {
'sucess': False, 'message': 'Message could not be sent', 'status_code': 400, 'error': f'{error}', 'code': f'{code}'})
return message
def twilio_studio_flow(phone_number: str) -> str:
'''
Twilio Studio Flow
'''
response = request.values.get('Body', '').lower()
execution = twilio_client.studio \
.v2 \
.flows(Config.TWILIO_STUDIO_FLOW_SID) \
.executions \
.create(to=(f'whatsapp:{phone_number}'), from_=Config.TWILIO_PHONE_NUMBER,
parameters={
"appointment_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
})\
.update(status='ended')
def validate_phone_number(phone_number: str) -> bool:
'''
Validate phone number
'''
try:
phone = phonenumbers.parse(phone_number.strip(), None)
client = Client.query.filter_by(phone=phone_number).first()
return phonenumbers.is_valid_number(phone) and client is not None
except Exception:
return False
def incoming_message() -> str:
'''
Receive incoming messages
'''
# Get the message the user sent our Twilio number
incoming_message = request.values.get('Body', '').lower()
# Get the phone number of the person sending the text message
phone_number = request.values.get('From', None).replace('whatsapp:', '')
resp = MessagingResponse()
if validate_phone_number(phone_number) and incoming_message:
resp.message(twilio_studio_flow(phone_number))
else:
resp.message(
'Lo sentimos, no pudimos validar tu numero de telefono 😟')
return str(resp)
Thanks in advance for helping me :).
As I mentioned previously, I want to know the right way to execute a Twilio Studio. Honestly, I cheked the docs but it's a little bit unclear on how to this.
Based on your answer in the comments, I'd suggest to link the Studio flow directly to the WhatsApp sender in the console (instead of invoking the flow manually via the API).
To connect the Studio Flow to your WhatsApp number ("Sender"). Click on the Trigger (Start) Widget and locate the Webhook URL field in the right-hand menu. Copy that URL to your clipboard.
Next, navigate to your WhatsApp Senders in the Twilio console. Click to select the sender that you want to use with this Studio Flow. Paste the Webhook URL that you copied from your Studio Flow into the field Webhook URL for incoming messages. Don't forget to click Update WhatsApp Sender.
Now, any time you receive an inbound message on your selected WhatsApp-enabled sender (number), it will be routed to your new Studio Flow.
Taken from the documentation.
Im trying to write a script in python that listen "first reply" of a bot and then exits. So, I create a client instance and then send a msg to Bot and now I want to record only first reply of bot (upcoming replies can ignored), and save bot reply to Reply variable. Now how to exit from listener mode so that I can do other stuffs after getting reply. I tried client.disconnect() and client.disconnected() but now working or maybe I don't know proper use of these method. I'm new to telethon APIs.
When I run this script, a msg from my telegram is sent to
bot(BotFather) and then bot send a reply
Reply from bot father
I can help you create and manage Telegram bots. If you're new to the
Bot API, please see the manual (https://core.telegram.org/bots).
You can control me by sending these commands:
/newbot - create a new bot /mybots - edit your bots [beta]
Edit Bots /setname - change a bot's name /setdescription - change bot
description /setabouttext - change bot about info /setuserpic - change
bot profile photo /setcommands - change the list of commands
/deletebot - delete a bot
Bot Settings /token - generate authorization token /revoke - revoke
bot access token /setinline - toggle inline mode
(https://core.telegram.org/bots/inline) /setinlinegeo - toggle inline
location requests
(https://core.telegram.org/bots/inline#location-based-results)
/setinlinefeedback - change inline feedback
(https://core.telegram.org/bots/inline#collecting-feedback) settings
/setjoingroups - can your bot be added to groups? /setprivacy - toggle
privacy mode (https://core.telegram.org/bots#privacy-mode) in groups
Games /mygames - edit your games
(https://core.telegram.org/bots/games) [beta] /newgame - create a new
game (https://core.telegram.org/bots/games) /listgames - get a list of
your games /editgame - edit a game /deletegame - delete an existing
game
and this reply got assigned in Reply variable
but my scripts
still listening for other upcoming events. is there any method from
which I can close this connection.
import random
import traceback
import configparser
from telethon import TelegramClient, events, sync
from telethon.errors import SessionPasswordNeededError
from telethon.errors.rpcerrorlist import PeerFloodError
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.messages import GetDialogsRequest,GetHistoryRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, PeerChannel
api_id = #Api_ID
api_hash = #Api_Hash
phone = #session
client = TelegramClient(phone, api_id, api_hash)
Reply = ' '
#client.on(events.NewMessage(chats='https://t.me/BotFather'))
async def NewMessageListener(event):
Reply = event.message.message
with client:
client.send_message("https://t.me/BotFather", "/start")
client.run_until_disconnected()
# Disconnect client to stop run_until_disconnected()
# Do other stuff!!!
I don't understand what you trying to achieve here but you can disconnect the client using disconnect method
from telethon import TelegramClient, events
api_id = #Api_ID
api_hash = #Api_Hash
phone = #session
client = TelegramClient(phone, api_id, api_hash)
Reply = ' '
#client.on(events.NewMessage(chats='https://t.me/BotFather'))
async def newMessageListener(event):
reply = event.message.message
# do stuff with reply then close the client
await client.disconnect()
async def main():
async with client:
await client.send_message("https://t.me/BotFather", "/start")
await client.run_until_disconnected()
I am using python telethon module. I want to send some messages having media files from a public telegram channel to a user using bot. I get the required message by GetMessagesRequest function by logging in as a telegram client i.e. not as bot and channel info using get_entityas bot.
channelInfo=await BOT.get_entity(tl.types.PeerChannel(channelId))
MSG = await CLIENT(functions.channels.GetMessagesRequest( channel=channelInfo.username, id=[MessageId]))
Forward_MSG = MSG.messages[0]
Using await BOT.send_message(USER, MSG) or await BOT.send_file(USER, MSG) gives telethon.errors.rpcerrorlist.MediaEmptyError: The provided media object is invalid (caused by SendMediaRequest)
Using await BOT.forward_messages(USER, MSG) gives TypeError: Cannot cast NoneType to any kind of Peer.
How can I send Forward_MSG to a user as a bot ?
I was trying to buid an app to send push notification throguh dialogflow fullfuillment to user. I followed this link, now I've got the update permission (see screenshot 1 and 2 at the bottom of the quetion). I followed the stackoverflow thread to write this piece of python code to send a notification, I'm able to run it, and got a status code of 200, but I never receive my test notification on my GoogleHomeApp/Google speaker. Can you help?
import io
import json
import requests
from google.oauth2 import service_account
import google.auth.transport.requests
PATH_TO_SERVICE_ACCOUNT = 'account.json'
REQUIRED_SCOPE = 'https://www.googleapis.com/auth/actions.fulfillment.conversation'
# Get access token
with io.open(PATH_TO_SERVICE_ACCOUNT, 'r', encoding='utf-8') as json_fi:
credentials_info = json.load(json_fi)
credentials = service_account.Credentials.from_service_account_info(
credentials_info, scopes=[REQUIRED_SCOPE])
request = google.auth.transport.requests.Request()
credentials.refresh(request)
headers = {
'Authorization': 'Bearer ' + credentials.token
}
text = 'Hello, this is a test notification'
user_id = "ABwppHFyNFT1fqDRmEug_k2ZKu43hM7xbLmgShN_ESww0iwPLQh-BU6n4T-e3rUOiVqRBWNn5q6bOg"
payload = {
'customPushMessage': {
'userNotification': {
'title': 'Recent News',
'text': text,
},
'target': {
'userId': user_id,
'intent': 'Recent News',
# Expects a IETF BCP-47 language code (i.e. en-US)
'locale': 'en-US'
}
}
}
r = requests.request("POST", 'https://actions.googleapis.com/v2/conversations:send', data=json.dumps(payload), headers=headers)
print(f"A push notification has been sent to user {user_id} with status code {r.status_code}.")
This is the screenshot of simulator:
This is the logs I got on my localhost, shows that I got the permission to send push notification to the user.
I went to the stackdriver logging to check the logs, this is what i got:
If you go to the Official Push Notifications Documentation you'll find the note which indicates that as of now, push notifications are not supported on the voice-activated speakers.
Soon they might release the update but we never know! You might ask the support team regarding the updates.
I am looking over the following code which does a 'group chat' with different members:
# Receive message from WebSocket
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': 'OK'
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))
My questions is what do the two items do? I see that receive(), also does the group_send, so what purpose does the chat_message have if the receive sends it upon receiving it?
That chat server code is a simple example on how to send group messages.
In the code:
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': 'OK'
}
)
this line
'type': 'chat_message',
is responsible for calling method chat_message() with { 'message': 'OK'}
Before sending this message to the group members you may want to modify or check the data, or need to do other stuff. That's why self.channel_layer.group_send doesn't directly sends message to the group but calls another method (in this case chat_message) to handle sending of message and to keep receive() method's code clean.