Sending Facebook message - python

Just trying to send a Facebook message with python.
Code:
import fbchat
from fbchat import Client
from fbchat.models import *
client = Client("my_username", "my_password")
#help(fb.Client.send)
#client.send(text="This is a test", thread_id="christopher.batey", thread_type=ThreadType.USER)
name = "christopher.batey"
friends = client.searchForUsers(name)
friend = friends[0]
uid = friend.uid
msg = "This is a test"
print(help(client.send))
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
Error:
Traceback (most recent call last):
File "main.py", line 13, in
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
TypeError: init() got an unexpected keyword argument 'thread_id'

I'm not familiar with the API but from the documentation, it looks like the proper call would be:
client.send(Message(text=msg), thread_id="christopher.batey", thread_type=ThreadType.USER)
where the message object is the first argument passed into send, followed by thread_id and thread_type.

I spent some time exploring this module a few years ago.
Quickly looking back at the github examples the the thread_id should be a number.
As such change
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
to
client.send(Message(text=msg), thread_id=uid, thread_type=ThreadType.USER)
in your code. As your uid is that of the friend you want to send too.

Related

My friend is trying to make a facebook bot but we can't fix this error

here is his code
import facebook
import os
# Initialize the Graph API with your access token
graph = facebook.GraphAPI(access_token=os.getenv("TOKEN"), version="3.0")
# Get the current user's conversations
conversations = graph.get_object("me/conversations")
# Iterate through the conversations
for conversation in conversations['data']:
# Get the sender's ID and the message text
sender_id = conversation['messages']['data'][0]['from']['id']
message_text = conversation['messages']['data'][0]['message']
# Send an auto-reply to the sender
graph.put_object(parent_object=sender_id, connection_name="messages", message="Thank you for your message. I am a bot and will respond to you as soon as possible.")
but it returns
Traceback (most recent call last):
File "main.py", line 8, in <module>
conversations = graph.get_object("me/conversations")
File "/home/runner/Facebook-Bot/venv/lib/python3.8/site-packages/facebook/__init__.py", line 126, in get_object
return self.request("{0}/{1}".format(self.version, id), args)
File "/home/runner/Facebook-Bot/venv/lib/python3.8/site-packages/facebook/__init__.py", line 313, in request
raise GraphAPIError(result)
facebook.GraphAPIError: (#298) Reading mailbox messages requires the extended permission read_mailbox
We gave it the pages_messaging_phone_number, pages_messaging, read_page_mailboxes and we thought that would work
I tried asking OpenAI GPT-3 i thought that would give me an answer for some reason
Here Is The OpenAI GPT-3 response (the reason the image is on discord is because we made a discord bot that uses OpenAI GPT-3 for AI prompts)

tried to make a discord bot , but gave an error:

#cod
import discord
from discord.ext import commands
client = discord.Client(intents = discord.Intents().all)
Traceback (most recent call last):File "E:\PyCharm\bot\Bot_state.py", line 4, in client = discord.Client(intents = discord.Intents().all)File "E:\PyCharm\bot\lib\site-packages\discord\client.py", line 248, in __init__self._connection = self._get_state(**options)File "E:\PyCharm\bot\lib\site-packages\discord\client.py", line 265, in _get_statereturn ConnectionState(dispatch=self.dispatch, handlers=self._handlers,File "E:\PyCharm\bot\lib\site-packages\discord\state.py", line 152, in __init__raise TypeError('intents parameter must be Intent not %r' % type(intents))TypeError: intents parameter must be Intent not <class 'method'>
You forgot to call all(). The error message therefore is saying that you are trying to pass the method all as argument instead of an Intent (what calling all() is supposed to return).
Here is the correct piece of code:
#cod
import discord
from discord.ext import commands
client = discord.Client(intents = discord.Intents().all())

Creating New Contact Google People API

I was following the guide:
https://developers.google.com/people/v1/write-people
My Code:
def main():
"""Shows basic usage of the Google People API
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('people', 'v1', http=http,
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
contact2 = service.people().createContact(
body={"names": [{"givenName": "John", "familyName": "Doe"}]}).execute()
contact2()
if __name__ == '__main__':
main()
When i run, My Error:
~/quickstart.py
Traceback (most recent call last):
File "~/quickstart.py", line 77, in <module>
main()
File "~/quickstart.py", line 66, in main
contact2()
TypeError: 'dict' object is not callable
Process finished with exit code 1
I am getting this error. How do I effectively create a new contact?
Your problem is this line:
contact2()
service.people().createContact returns dictionary as response and you are trying to call it.
dictionary object is not a function.
Problem solved, although I do not understand why. I was able to save contact using:
contact2 = service.people().createContact(
body={"names": [{"givenName": "John", "familyName": "Doe"}]})
contact2.execute()

SparkPost: At least one valid recipient is required python/django API

I have a problem sending email with SparkPost:
My code is as follow:
from configurations.global_configs import site_base_url
from media.settings import SPARKPOST_API_KEY
from sparkpost import SparkPost
import traceback
def welcome_email(user_profile):
try:
user_profile.confirmation_key = user_profile.generate_key()
user_profile.save()
email_address = user_profile.user.email
print email_address
name = user_profile.user.first_name or email_address
email_confirmation_url = site_base_url + "api/account/signup/?ck=" + user_profile.confirmation_key
print email_confirmation_url
sp = SparkPost(SPARKPOST_API_KEY)
result = sp.transmissions.send(
recipients=[email_address],
template='welcome',
subject='this is my subject',
track_opens=True,
track_clicks=True,
substitution_data={
'email_validation_url': email_confirmation_url
},
transactional= True
)
return result
except:
traceback.print_exc()
but my code output is as follows and returns this error:
exampleemail#gmail.com
http://example.com/api/account/signup/?ck=1144f138439dc42e
Traceback (most recent call last):
File "./users_system/services/email_confirm.py", line 28, in welcome_email
transactional= True
File "/usr/local/lib/python2.7/dist-packages/sparkpost/transmissions.py", line 142, in send
results = self.request('POST', self.uri, data=json.dumps(payload))
File "/usr/local/lib/python2.7/dist-packages/sparkpost/base.py", line 26, in request
raise SparkPostAPIException(response)
SparkPostAPIException: Call to https://api.sparkpost.com/api/v1/transmissions returned 400, errors:
At least one valid recipient is required:
As you can see I have one recipient and I know that is valid because I sent test mail via sparkpost dashboard. But why I get this error "At least one valid recipient is required" ??!!! where is my problem
I found the answer, First I want to thank Sparkpost support team the issue was in email parser in spark module and the issue is created for solving it in my code I made this change to fix it:
recipients=[ dict(address=dict(email=email_address)) ],
Since you are using it as a django backend for your email, why don't you do this directly with the
from django.core.mail import send_mail
send_mail(
subject='hello from sparkpost',
message='Hello Rock stars!'
from_email='from#yourdomain.com',
recipient_list=['to#friendsdomain.com'],
html_message='<p>Hello Rock stars!</p>',
)
as mentioned in their official docs

Difficulties with sending mail from GAE

I'm trying to send an email from within Google App Engine.
Whenever I try to send, I get a "Missing subject error".
When I run the code on the development server, it seems to work fine - the console output looks right and I'm taken to the page that I was expecting. But when I upload it and run it, I get:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__
handler.post(*groups)
File "/base/data/home/apps/spam-tool/1.349401522260793315/spam-tool.py", line 34, in post
body=cgi.escape(self.request.get('content')))
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 297, in send_mail
message.send(make_sync_call)
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 799, in send
raise ERROR_MAP[e.application_error](e.error_detail)
BadRequestError: Missing subject
But there's definitely a subject.
The code I'm using is:
> message = mail.EmailMessage(sender="admin_address#gmail.com>",
subject="test")
message.subject=self.request.get('content')
message.to = addr_to_send_to
message.body = self.request.get('content')
message.send()
(Yes, the subject is set twice... I've tried only setting it in one place or the other, and neither worked.)
Thanks in advance.
Try this:
def email_member(request):
to_addr = request.POST.get('email_to')
if not mail.is_email_valid(to_addr):
# Return an error message...
pass
else:
# note we can also send html email, e.g. html='<html><head></head><body>Hello world</body><html>'
mail.send_mail(
sender='admin#yourdomain.com',
to=to_addr,
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'))
I suggest you also send your email within the taskqueue, so you could setup something like this, you could pass over a unique parameter so that you are less likely to be hacked.
def mail_member_information(email_to, email_title, email_body):
taskqueue.add(
url = 'email_message',
params =
{
'email_to': email_to,
'email_title': email_title,
'email_body': email_body,
'valid_guid': 'ae9e34ca-a2c5-476e-b8be-72d807e3dc6b'
}
)
If you just want to send to the administrators then use this:
mail.send_mail_to_admins(sender='admin#yourdomain.com',
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'),
html=request.POST.get('email_body'))
I don't know if it is what is throwing you off... but sender should be like this:
sender = '<admin_address#gmail.com>',
you are missing the '<' for the sender. Sometimes it throws an error downstream of where the actual error is.
Also, make sure the admin_address#gmail.com is a Google Account that has been added as a developer for that app.
I think you can send like this, make sure that sender is a admin of the app
from google.appengine.api import mail
mail.send_mail(sender="something#gmail.com",
to=email_valid.email,
subject="Please validate your email",
body=body_text,
html=htmlbody_text)

Categories