Whatsapp bot using Twilio and Flask- Wait for Reply - python-3.x

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

Related

What's the right way to execute a Twilio Studio conversation flow?

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.

Trouble with limit access to a Telegram Bot

I am really new to python and I want my bot answers only limit users by their username.
I am trying to code this feature, but my bot send only one message "Not authorized".
What is wrong?
number_list.append(choice)
if update.effective_user.username not in ["username"]:
query.edit_message_text(text="Not authorized")
return
You can use telebot api
import telebot
bot = telebot.TeleBot("TOKEN")
username = ["USERNAME"]
#bot.message_handler(content_types=["text"])
def default_test(message):
if message.from_user.username not in username:
bot.send_message(message.chat.id, "Not authorized")
else:
bot.send_message(message.chat.id, "Authorized")
bot.polling(none_stop=True)

Discord bot function stops working when in a guild with other specific bots

Ok, So..I have made an on guild join captcha for my bot. Works how you'd think it would work. User joins, gets a DM with a captcha, user completes the captcha, they get access/a role. They fail the captcha, it regens a new one and says try again.
The following code works flawlessly and without error except for when it can't DM a user (not my issue that I need help with).
HOWEVER, and idk if this has anything to do with my code or discord intents or other discord bots in the same server my bot is in..but when the bot is in a server alone with no other bots, works flawlessly with all functionality. The moment I have the bot in the server with Welcomer bot for example. It generates the captcha, sends it to the user, then nothing.. no response, no error on my end. Just nothing. The user can send the captcha answer all they want but they get no response, no role, no error or new captcha. The rest of the bots commands and code still work and the bot remains online.
I know the code works and functions fully because I just tested it multiple times with many different people including myself.
It's just when it is in the same server with other bots that it just stops working. Some bots don't interfere but others do and I have no way of telling until I start kicking them until I find the one stopping my bots DM captcha stuff from working. Like welcomer bot. I know it sounds weird but it's true. I've spent literal weeks testing this out and this is all just what I've found out. I am honestly out of ideas..
Like I said, idk if it has anything to do with the discord bots intents or my code. I was hoping someone here could have answers or an explanation.
This is what I have for my bots intents.
intents = discord.Intents.default()
intents.members = True
BOT_Prefix=("t.", "T.")
eye = commands.Bot(command_prefix=BOT_Prefix, intents=intents) #eye replaces Client. So instead of #Client.command/event it's #eye.command/event.
And this is the captcha code/function.
#eye.event
async def on_member_join(user: discord.Member):
while True:
verified = discord.utils.get(user.guild.roles, id=649739504940351489)
res = r.get("https://captcha.manx7.net/insecure/new", headers={"captcha-length":"5"}).json();
if res['error']:
print(res['error'] + " - Manx7 Error")
user.send("Something went wrong while trying to set-up a captcha session, please contact `" + bot_author + "` for help.")
return
captcha_answer = res['response']['code']
embed = discord.Embed(title="Server Captcha", description=f"```fix\nHello {user.name},\nYou will not be able to gain access to the server until you complete this captcha.\nPlease Type The Follwoing Below To Verify!!\n\nNotes:\n1)The letters are case sensitive and are the big colorful ones.\n\n2)DM " + bot_author + " if the bot breaks or if you encounter any bugs!!\n\n-----------------------------\nCaptchca API - https://captcha.manx7.net/```")
embed.set_footer(text=f"{botver} by Ori", icon_url='https://cdn.discordapp.com/attachments/850592305420697620/850595192641683476/orio.png')
embed.set_image(url=res['response']['image'])
await user.send(embed=embed)
#Everything above this line/message works fine every time.
msg = await eye.wait_for("message")
if msg.author.id == eye.user.id:
return #Ignores itself (Used to send captcha, error then send it again when a user joined. This stops that.)
if msg.author.bot:
return #Ignores bots
if msg.content == captcha_answer:
embed2 = discord.Embed(title="Verified!", description=f":white_check_mark: Thank you for verifying!. You have now been given access to the server!", color=discord.Color.green())
embed2.set_footer(text=f"{botver} by Ori", icon_url='https://cdn.discordapp.com/attachments/850592305420697620/850595192641683476/orio.png')
await user.send(embed=embed2)
await user.add_roles(verified, reason="None")
break
else:
embed3 = discord.Embed(title="Error!", description="\n\n__Captcha Failed, Please Try Again__\n\n", color=discord.Color.red())
await user.send(embed=embed3)
pass
Your guess is as good as mine. This has been an issue of mine for weeks now going on a month..
Any help is appreciated.
Since no check kwarg was provided in your wait_for, it will take input from all users, including bots + in any channel visible to the bot.
So, when a user joins and welcomer post its welcome message in a channel
if msg.author.bot:
return #Ignores bots
is triggered
Do notice, you are returning and not passing so it returns and after that your wait_for becomes useless
define a check function and use the following check kwarg inside your wait_for constructor
def check(m):
return m.author == user and m.channel == x.channel
so your code now becomes:
#eye.event
async def on_member_join(user): # you need not typecast in an event, it by default knows that user is a discord.Member object
while True:
verified = discord.utils.get(user.guild.roles, id=649739504940351489)
res = r.get("https://captcha.manx7.net/insecure/new", headers={"captcha-length":"5"}).json();
if res['error']:
print(res['error'] + " - Manx7 Error")
user.send("Something went wrong while trying to set-up a captcha session, please contact `" + bot_author + "` for help.")
return
captcha_answer = res['response']['code']
embed = discord.Embed(title="Server Captcha", description=f"```fix\nHello {user.name},\nYou will not be able to gain access to the server until you complete this captcha.\nPlease Type The Follwoing Below To Verify!!\n\nNotes:\n1)The letters are case sensitive and are the big colorful ones.\n\n2)DM " + bot_author + " if the bot breaks or if you encounter any bugs!!\n\n-----------------------------\nCaptchca API - https://captcha.manx7.net/```")
embed.set_footer(text=f"{botver} by Ori", icon_url='https://cdn.discordapp.com/attachments/850592305420697620/850595192641683476/orio.png')
embed.set_image(url=res['response']['image'])
x = await user.send(embed=embed)
#Everything above this line/message works fine every time.
def check(m): # m is a Message object
return m.author == user and m.channel == x.channel # return only if the user responded in bot's dms and user is the person who triggered the event
msg = await eye.wait_for("message", check=check)
if msg.author.id == eye.user.id:
return #Ignores itself (Used to send captcha, error then send it again when a user joined. This stops that.)
if msg.content == captcha_answer:
embed2 = discord.Embed(title="Verified!", description=f":white_check_mark: Thank you for verifying!. You have now been given access to the server!", color=discord.Color.green())
embed2.set_footer(text=f"{botver} by Ori", icon_url='https://cdn.discordapp.com/attachments/850592305420697620/850595192641683476/orio.png')
await user.send(embed=embed2)
await user.add_roles(verified, reason="None")
break
else:
embed3 = discord.Embed(title="Error!", description="\n\n__Captcha Failed, Please Try Again__\n\n", color=discord.Color.red())
await user.send(embed=embed3)
pass

Twilio WhatsApp bug

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.

How to make discord bot automatically send direct message [Discord.py]

I can send direct message through discord bot if I type something to trigger the event. But I don't know the way to let discord bot automatically send direct message when It meet specific condition
Here is my code for your query:
To make it send on command, do:
#bot.command()
async def dm(ctx):
await ctx.author.send("Hello, this is a DM!")
and then to make it send on an on_message trigger do:
#bot.event
async def on_message(message):
if "dm" == message.content.lower()
await message.author.send("Hello, this is a DM!")
What happens is to send a dm, send a message to the author. It's as simple as that. But for the on_message, we check if the message is "dm" in which case it dm's you.
You would first setup your bot and have it run. An example of this would be
#bot.event
async def on_message(message):
if "this triggers" in message.content:
await message.author.send("I just dmed you this message")
To check if it is in a guild message.guild != None will return True and message.guild.id == 1232131231231 will check if the guild's/server's id is 1232131231231

Resources