I have code for scanning phone numbers to put into the correct format and then have the SMS sent to the phone number. Although, I don't know how to apply this the "best" way.
In my create method I have:
if #order.phone_number.present?
account_sid = '1234567890'
auth_token = '1234567890'
client = Twilio::REST::Client.new(account_sid, auth_token)
message = client.messages.create(
from: '+12017541209',
to: '+120188854064',
body: "You received Order from #{#order.listing.name} - View it here: localhost.com/order/#{#order.order_token}/order_confirmation" )
end
I then have this code for scanning:
def clean_number
number = self.phone_number.scan(/\d+/).join
number[0] == "1" ? number[0] = '' : number
number unless number.length != 10
end
The format I need is 11231234567
Whether the text_input is:
1-123-123-1234
123-123-1234
+1(123)-123-1234
etc.
Now, the SMS works but I haven't applied the clean_number method yet. Should i be putting this in my model, and then call it in the controller, or have it in the private within the controller?
Related
email user specific developer jobs at a given location
import requests # for api
import smtplib # for emails
import auth
class Jobs:
URL = "https://jobs.github.com/positions" # base url for API
def _jobs_api(self): # get json data (jobs)
location = input("Where would you like to become a developer? \U0001f607\n") # location parameter
description = input("What type of developer are you interested in becoming? \U0001f608\n") # search term
response = requests.get(Jobs.URL,
headers={"Accept": "application/json"},
params={"location": location, "description": description} # query params
)
data = response.json()
return data
def _job_links(self):
data = self._jobs_api()
if data:
for job in data:
links = job['url']
return links
else:
print(f"Sorry, I was not able to find any {self.description} jobs in {self.location}...")
def send_jobs(self): # email auth
links = self._job_links()
smpt_object = smtplib.SMTP('smtp.gmail.com', 587)
smpt_object.ehlo()
smpt_object.starttls()
# use own authentication data
email = auth.email()
password = auth.password()
smpt_object.login(email, password)
# next, send the message
from_address = email
to_address = email
subject = "Developer Jobs"
message = "Here are some jobs you are looking for: {}".format(links)
msg = "Subject: "+subject+"\n"+message
print("Check your email for an update! \U0001f601")
smpt_object.sendmail(from_address, to_address, msg)
smpt_object.quit()
user = Jobs()
user.send_jobs()
I'm trying to use the line Here are some jobs you are looking for: {}".format(links) (or an f string preferably) to send the links found from the API. But, when I check my email, it doesn't show the message with the links.
You can try to send a html structured mail in python to send the url you want.
See this post to find out
I am trying to check/filter through users inbox emails and check for keywords "offer" and "letter"
from calling messages on gmail api it returns the message id and threads which you can use to get the message contents that I have added to an array from my example below
def keyword_check
client = Signet::OAuth2::Client.new(access_token: session[:access_token])
service = Google::Apis::GmailV1::GmailService.new
service.authorization = client
messages = service.list_user_messages('me')
#messages_json = []
messages.messages.each do |m|
response = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages/#{m.id}?access_token=#{session[:access_token]}")
res = JSON.parse(response.body)
#messages_json << res
end
filter = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages?q=offer?access_token=#{session[:access_token]}")
mes = JSON.parse(filter.body)
render json: #messages_json.to_json
end
this returns all the messages in an array but I am finding it difficult filtering the array and checking for the particular keywords and returning both a boolean of true or false and the message itself alone in the array?
I think you should check whether the keywords are present in the response.body before adding them to the array:
def keyword_check
client = Signet::OAuth2::Client.new(access_token: session[:access_token])
service = Google::Apis::GmailV1::GmailService.new
service.authorization = client
messages = service.list_user_messages('me')
#messages_json = []
messages.messages.each do |m|
response = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages/#{m.id}?access_token=#{session[:access_token]}")
res = JSON.parse(response.body)
#messages_json << res if matches_keywords(response.body)
end
filter = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages?q=offer?access_token=#{session[:access_token]}")
mes = JSON.parse(filter.body)
render json: #messages_json.to_json
end
def matches_keywords content
return true if content.include?('offer')
return true if content.include?('letter')
return false
end
Edit: Be aware that the body probably contains all the HTML formatting, css code etcetera... suppose for instance that there's a CSS rule with 'letter-spacing', the new function will always return true, so please check whether you are able to get the TEXT content instead. For this, have a look at the documentation for the Gmail API.
Another approach could be to use Kaminara (or equivalent) to really dive into the HTML structure, and only check the part that holds the actual text ( or some specific or something)
I have to setup my rails project to send a confirmation SMS to new users. I have a table phone_calling_codes which has a column sms_enable_flag. In my DB this field has to be checked or not, so it's boolean.
I use Twilio to send SMS but I want to add a condition to send SMS only to the numbers where this sms_enable_flag is checked.
I also use phonelib to parse the number and take the country code from it.
def perform(phone_number, confirmation_code)
logger.info("Job started sending confirmation code")
overrideToPhone = [ "development","upgrade"].include? Rails.env
deliverSMS = !([ "development", "upgrade"].include? Rails.env)
phone=''
if overrideToPhone
e164Prefix = '+'
phone_number = e164Prefix + "17782002024"
else
phone = Phonelib.parse( phone_number)
phone_number = phone.e164
end
sms=phone_calling_codes.find_by calling_code: phone.country_code
if sms
if sms.sms_enabled_flag
from_phone_number = Rails.application.secrets.twilio_number
body = "Valorbit.com - your phone verification code is: #{confirmation_code}"
logger.info("From #{from_phone_number} to #{phone_number} : #{body}")
twilio_client.messages.create(
to: phone_number ,
from: from_phone_number ,
body: body
) if deliverSMS
logger.info("Sent sms to #{phone_number}") if deliverSMS
else
logger.info("SMS is not enabled for #{phone_number}")
end
end
end
Please help me to this. I am a beginner to OOP and I want to understand if it is ok how I have thought.
Thanks! :D
change line
sms=phone_calling_codes.find_by calling_code: phone.country_code
to
sms=PhoneCallingCode.find_by calling_code: phone.country_code
PhoneCallingCode is the model name present in /app/models folder
Below is the query to find data from model:
ModelName.find_by column_name: parameter
I'm currently trying to connect two users via twillio and am masking their identities. I am doing this by having:
User A dials my Twillio # ---> hits my app URL endpoint --> dials User B and has the call ID show up as my Twillio #
When trying this, the TwiML is being rendered with the dialed/forwarded number always blank. Even when I hardcode it, Twillio never forward the call anywhere.
def make_twillio_call_PSTN
incoming_number = params[:From]
#strip +1 from number
incoming_number = incoming_number.byte_slice(2,10)
response = Twilio::TwiML::Response.new do |r|
r.Dial callerId: MY_TWILIO_MOBILE do |d|
d.Number MY_NUMBER
end
render xml: response.to_xml
end
end
My team and I are using twilio to send sms messages. Everything seems to work fine on everyone else's local machine (with the same exact code) except twilio always returns an authenticate error to me. I'm sending the messages to their "special number" so it won't actually send a real text message but it still returns an authenticate error.
here's some of our code to send the message:
def send_sms
self.from_phone_number = CONFIG['live_twilio'] ? self.customer.assigned_phone_number : CONFIG['test_phone_number']
self.to_phone_number = CONFIG['live_twilio'] ? self.customer.customer_phone_number : CONFIG['test_phone_number']
begin
report_to_new_relic_insights
send_message_with_twilio!
rescue Twilio::REST::RequestError => e
self.error_description = e.message
end
self.dispatched_at = Time.now
self.save(validate: false)
return e
end
def send_message_with_twilio!
unless self.customer.example_customer?
twilio_params = {
from: "+1#{from_phone_number}",
to: "+1#{to_phone_number}",
body: self.text
}
if ENV['RECORD_TWILIO_STATUSES'].in?(['1', 'true'])
twilio_params[:status_callback] = "#{CONFIG['secure_domain']}/messages/#{id}/update_status"
end
client.account.messages.create(twilio_params)
else
# #onboarding_flow
# don't send the actual SMS to the example customer
self.customer.send_reply_as_example_customer! if self.customer.first_reply?
end
end
def client
#client ||= begin
account_sid = ENV['ACCOUNT_SID'] || CONFIG['account_sid']
auth_token = ENV['AUTH_TOKEN'] || CONFIG['auth_token']
Twilio::REST::Client.new account_sid, auth_token
end
end
every time this line runs: client.account.messages.create(twilio_params)
it returns authenticate error. it works on every other local machine except for mine. all of the code is exactly the same, the auth tokens are exactly the same. any ideas what the problem could be? (the auth tokens are getting pulled from config.yml
More info: even when running the bare bones twilio client in console with the same exact info in both machines, mine returns an error and my coworkers returns valid
Twilio evangelist here.
This could be one of many things, but the only reason Twilio would complain about authentication, is if you have a wrong account SID or auth token.
So can pretty much guarantee this is the bit that is going wrong:
def client
#client ||= begin
account_sid = ENV['ACCOUNT_SID'] || CONFIG['account_sid']
auth_token = ENV['AUTH_TOKEN'] || CONFIG['auth_token']
Twilio::REST::Client.new account_sid, auth_token
end
end
My suggestion here is for you to open up your terminal and run:
$ printenv
This should print all your environment variables for you. You're interested on ACCOUNT_SID and AUTH_TOKEN, so you could get those specific values from terminal as follows:
$ printenv | grep "ACCOUNT_SID\|AUTH_TOKEN"
Then check with your peers if you are using the same values. Please let me know the outcome.