cant iterate through members of a server discord API - api

import discord
import asyncio
from discord.ext import commands
client = commands.Bot(command_prefix=':')
token = ''
#client.event
async def on_ready():
print('BOT ONLINE')
#client.event
async def on_message(message):
channel = message.channel
if message.content.startswith('/'):
if message.content.startswith("/users"):
# FOR LOOP IN QUESTION ---------------
for guild in client.guilds:
for member in guild.members:
print(member) # or do whatever you wish with the member detail
client.run(token)
print("Bot Finished")
When I run this code all it returns is the bot name twice. The server has two members, myself and the bot. I need to iterate through every member of the server. What am I doing wrong?

You simply didn't enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=":", intents=intents)
Also make sure to enable them in the developer portal
Reference:
intents.members
How to enable privileged intents

Related

How can I convert Telegram Session String from Telegram Session file

I'm trying to get the Session String from an existing Session File of Pyrogram. How can I do that?
Can you help me?
from dotenv import dotenv_values
from pyrogram import Client
config = dotenv_values(dotenv_path='./.env')
app = Client(
# name="withstring",
name="my_bot",
# api_id=config.get("API_ID"),
# api_hash=config.get("API_HASH"),
bot_token=config.get("BOT_TOKEN"),
)
with app:
app.send_message("username", text="Hello world Minhaz!")
s = app.export_session_string()
# print(s)
app.run()
The Session File is an sqlite database storing your authorization against the API and peers you've met (messages received, chats joined, etc).
To get the Session String to authenticate in Memory (losing peers when you log in again), you can just call the Client.export_session_string() method.
Edit to add: If you already have a session file, you can use its name to log in, instead of creating a new in-memory session. If you have a my_account.session file, use Client("my_session") when instantiating your Client.
from pyrogram import Client
app = Client(":memory:")
with app:
session = app.export_session_string()
print(session)

Import Telethon Session AWS Lambda

I am trying to use Telethon with AWS Lambda. More precisely I am trying get messages from some public channels using client object.
Is there a way to import an existing session in AWS Lambda, in order to prevent Telegram/telethon to ask for a validation code (which is not possible to input) ?
Here is the code I am using to try to connect to telegram through telethon in AWS Lambda :
api_id== os.environ.get('TELEGRAM_API_ID')
api_hash = os.environ.get('TELEGRAM_API_HASH')
userName = os.environ.get('TELEGRAM_USERNAME')
phone = os.environ.get('TELEGRAM_PHONE')
os.chdir("/tmp")
client = TelegramClient(userName, api_id, api_hash)
Here is the session file I have imported in AWS Lambda through Layers (same name as userName) session file
But it seems the session file is not used/read as telethon is asking the verification code and phone number.
Anyone know how to fix this ? Thanks
It took some time, but I found a solution to this problem and ran a Telegram client on Lambda)
All you need to do is use a different session type, namely StringSession.
As indicated in the official documentation, all you need to do is generate a StringSession in your local environment, save the string in a file or local variables and use it in your lambda code.
Generate StringSession, you will see the output in your terminal in this case:
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
with TelegramClient(StringSession(), api_id, api_hash) as client:
print(client.session.save())
Save your newly created StringSession into environment variables in Lambda, as described here and now you can do something like this:
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
import os
string = os.environ.get('session') # env variable named "session"
with TelegramClient(StringSession(string), api_id, api_hash) as client:
client.loop.run_until_complete(client.send_message('me', 'Hi'))

How to delete telegram bot own messages?

What I want to achieve is that before I post new message via bot X I delete the previous messages that are posted by the same bot X. I'm looking at the method bot.delete_message but that requires message_id what means that I would need to store the id some-have locally. Is there any way around this? Like fetching bot own messages?
import python-telegram....
import time
current_message = None
def current_message_updater(new_message):
global current_message
# delete last message
if not current_message:
current_message.delete()
# send new message will return its message object,
# we assign it into current_message variable
new = bot.send_message(....., text=new_message)
current_message = new
# if all of this is happening in the same function
# you can do like this
def my handler():
message = bot.send_message(...., text="hi new user")
time.sleep(1)
message.delete()
another_one = bot.send_message(..., text="How are u?")

Hey could someone show me some code on a discord.py API? Using an api from a website

Im trying to create a fortnite API to give me all of the Leaked cosmetics with a discord bot and I just don't know where to get started! Could someone help! Thankyou
Here's an example of a simple bot that repeats what you say.
import discord # importing the discord.py library
from discord.ext import commands # extension of said library
# This defines the bot's command prefix and if the commands are case insensitive
bot = commands.Bot(command_prefix='-', case_insensitive='True')
#bot.event =
async def on_ready():
```
This is an event that prints to the console that the bot is online and ready to go.
```
print('Bot is ready!') # prints to console that the bot is ready.
#bot.command()
async def echo(ctx, *, msg):
```
This is a command that repeats what you say. Echo is the name. *, msg means that all the words listed after the command are repeated
```
await ctx.message.delete() # delete the command message the the user said
await ctx.send(msg) # say whatever the user wanted to say.
# bot token here. found in the discord developer website
bot.run(YOUR BOT'S TOKEN GOES HERE)
Here's an example of using a api inside a Cog
Necessary Imports:
from discord.ext import commands
from discord import Embed, Color
from aiohttp import ClientSession
from ast import literal_eval
A command to fetch random Chuck Norris jokes
#commands.command()
async def chuck(self, ctx):
ad = Embed(color=Color.dark_gold())
base = "https://api.chucknorris.io/jokes/random"
async with ClientSession() as session:
data = await get(session, base)
data = literal_eval(data)
ad.set_author(name="Chuck Norris",
icon_url="https://i.ibb.co/swZqcK7/norris.gif",
url=data['url'])
ad.description = data['value']
return await ctx.send(embed=ad)
If you're getting information from Fortnite, chances are they already have a Python Module on PyPi, alternatively you can look for a JSON endpoint and apply what I did above to get what you need.

Google Analytics Management API - Insert method - Insufficient permissions HTTP 403

I am trying to add users to my Google Analytics account through the API but the code yields this error:
googleapiclient.errors.HttpError: https://www.googleapis.com/analytics/v3/management/accounts/**accountID**/entityUserLinks?alt=json returned "Insufficient Permission">
I have Admin rights to this account - MANAGE USERS. I can add or delete users through the Google Analytics Interface but not through the API. I have also added the service account email to GA as a user. Scope is set to analytics.manage.users
This is the code snippet I am using in my add_user function which has the same code as that provided in the API documentation.
def add_user(service):
try:
service.management().accountUserLinks().insert(
accountId='XXXXX',
body={
'permissions': {
'local': [
'EDIT',
]
},
'userRef': {
'email': 'ABC.DEF#gmail.com'
}
}
).execute()
except TypeError, error:
# Handle errors in constructing a query.
print 'There was an error in constructing your query : %s' % error
return None
Any help will be appreciated. Thank you!!
The problem was I using a service account when I should have been using an installed application. I did not need a service account since I had access using my own credentials.That did the trick for me!
Also remember that you have to specify the scope you would like to use, this example here (using the slightly altered example by Google) defines by default two scopes which would NOT allow to insert users (as they both give read only permissions) and would result in "Error 403 Forbidden" trying so.
The required scope is given in the code below:
from apiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.service_account import ServiceAccountCredentials
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Do something, e.g. get account users & insert new ones
# ...
def main():
# Define the auth scopes to request.
# Add here
# https://www.googleapis.com/auth/analytics.manage.users
# to be able to insert users as well:
scopes = [
'https://www.googleapis.com/auth/analytics.readonly',
'https://www.googleapis.com/auth/analytics.manage.users.readonly',
]
key_file_location = 'my_key_file.json'
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=scopes,
key_file_location=key_file_location)
profile_id = get_first_profile_id(service)
print_results(get_results(service, profile_id))
if __name__ == '__main__':
main()
Regards,
HerrB92