Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
added slack events api
paperboardofficial1dd66f3f038a
diff --git a/examples/integrations/slack_api.py b/examples/integrations/slack_api.pynew file mode 100644index 000000000..0a6acddaa--- /dev/null+++ b/examples/integrations/slack_api.py@@ -0,0 +1,102 @@+import logging+from browser_use import BrowserConfig+from fastapi import FastAPI, Request, HTTPException, Depends+from dotenv import load_dotenv+from slack_sdk.web.async_client import AsyncWebClient+from slack_sdk.errors import SlackApiError+from slack_sdk.signature import SignatureVerifier+from browser_use.agent.service import Agent, Browser+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_openai import ChatOpenAI++load_dotenv()++app = FastAPI()++logger = logging.getLogger(__name__)++class SlackBot:+ def __init__(self, llm: BaseChatModel, bot_token: str, signing_secret: str, ack: bool = False, browser_config: BrowserConfig = BrowserConfig(headless=True)):+ self.llm = llm+ self.ack = ack+ self.browser_config = browser_config+ self.client = AsyncWebClient(token=bot_token)+ self.signature_verifier = SignatureVerifier(signing_secret)+ self.processed_events = set()+ logger.info("SlackBot initialized")++ async def handle_event(self, event):+ try:+ event_id = event.get('event_id')+ if event_id in self.processed_events:+ logger.info(f"Event {event_id} already processed")+ return+ self.processed_events.add(event_id)++ if 'subtype' in event and event['subtype'] == 'bot_message':+ return++ text = event.get('text')+ user_id = event.get('user')+ if text and text.startswith('$bu '):+ task = text[len('$bu '):].strip()+ if self.ack:+ try:+ await self.send_message(event['channel'], f'<@{user_id}> Starting browser use task...', thread_ts=event.get('ts'))+ except Exception as e:+ logger.error(f"Error sending start message: {e}")++ try:+ agent_message = await self.run_agent(task)+ await self.send_message(event['channel'], f'<@{user_id}> {agent_message}', thread_ts=event.get('ts'))+ except Exception as e:+ await self.send_message(event['channel'], f'Error during task execution: {str(e)}', thread_ts=event.get('ts'))+ except Exception as e:+ logger.error(f"Error in handle_event: {str(e)}")++ async def run_agent(self, task: str) -> str:+ try:+ browser = Browser(config=self.browser_config)+ agent = Agent(task=task, llm=self.llm, browser=browser)+ result = await agent.run()++ agent_message = None+ if result.is_done():+ agent_message = result.history[-1].result[0].extracted_content++ if agent_message is None:+ agent_message = 'Oops! Something went wrong while running Browser-Use.'++ return agent_message++ except Exception as e:+ logger.error(f"Error during task execution: {str(e)}")+ return f'Error during task execution: {str(e)}'++ async def send_message(self, channel, text, thread_ts=None):+ try:+ await self.client.chat_postMessage(channel=channel, text=text, thread_ts=thread_ts)+ except SlackApiError as e:+ logger.error(f"Error sending message: {e.response['error']}")+[email protected]("/slack/events")+async def slack_events(request: Request, slack_bot: SlackBot = Depends()):+ try:+ if not slack_bot.signature_verifier.is_valid_request(await request.body(), dict(request.headers)):+ logger.warning("Request verification failed")+ raise HTTPException(status_code=400, detail="Request verification failed")++ event_data = await request.json()+ if 'challenge' in event_data:+ return {"challenge": event_data['challenge']}++ if 'event' in event_data:+ try:+ await slack_bot.handle_event(event_data['event'])+ except Exception as e:+ logger.error(f"Error handling event: {str(e)}")++ return {}+ except Exception as e:+ logger.error(f"Error in slack_events: {str(e)}")+ raise HTTPException(status_code=500, detail="Internal Server Error")\ No newline at end of filediff --git a/examples/slack_example.py b/examples/slack_example.pynew file mode 100644index 000000000..e1a2fe578--- /dev/null+++ b/examples/slack_example.py@@ -0,0 +1,63 @@+"""+This example requires you to have a Slack bot token and signing secret.++Steps to create and configure a Slack bot:++1. Create a Slack App:+ * Go to the Slack API: https://api.slack.com/apps+ * Click on "Create New App".+ * Choose "From scratch" and give your app a name and select the workspace.+2. Configure the Bot:+ * Navigate to the "OAuth & Permissions" tab on the left side of the screen.+ * Under "Scopes", add the necessary bot token scopes (e.g., "chat:write", "channels:history", "im:history").+ * Install the app to your workspace and copy the "Bot User OAuth Token".+3. Enable Event Subscriptions:+ * Navigate to the "Event Subscriptions" tab.+ * Enable events and add the necessary bot events (e.g., "message.channels", "message.im").+ * Add your request URL (you can use ngrok to expose your local server if needed).+4. Save the "Signing Secret" from the "Basic Information" tab.+5. Add the bot to your Slack workspace.+6. Run the code below to start the bot with your bot token and signing secret.+7. Write e.g. "$bu whats the weather in Tokyo?" to start a browser-use task and get a response inside the Slack channel.+"""++import os+from dotenv import load_dotenv+from integrations.slack_api import SlackBot, app+from langchain_google_genai import ChatGoogleGenerativeAI+from pydantic import SecretStr+from browser_use import BrowserConfig+from fastapi import Depends++load_dotenv()++# load credentials from environment variables+bot_token = os.getenv('SLACK_BOT_TOKEN')+if not bot_token:+ raise ValueError('Slack bot token not found in .env file.')++signing_secret = os.getenv('SLACK_SIGNING_SECRET')+if not signing_secret:+ raise ValueError('Slack signing secret not found in .env file.')++api_key = os.getenv('GEMINI_API_KEY')+if not api_key:+ raise ValueError('GEMINI_API_KEY is not set')++llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))++slack_bot = SlackBot(+ llm=llm, # required; instance of BaseChatModel+ bot_token=bot_token, # required; Slack bot token+ signing_secret=signing_secret, # required; Slack signing secret+ ack=True, # optional; whether to acknowledge task receipt with a message, defaults to False+ browser_config=BrowserConfig(+ headless=True+ ), # optional; useful for changing headless mode or other browser configs, defaults to headless mode+)++app.dependency_overrides[SlackBot] = lambda: slack_bot++if __name__ == "__main__":+ import uvicorn+ uvicorn.run("integrations.slack_api:app", host="0.0.0.0", port=3000, reload=True)\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex 4d44b530e..e21a9aec0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -29,7 +29,10 @@ dependencies = ["posthog>=3.7.0","playwright>=1.49.0","setuptools>=75.8.0",- "lmnr[langchain]>=0.4.53"+ "lmnr[langchain]>=0.4.53",+ "fastapi==0.115.7",+ "uvicorn==0.34.0",+ "slack_sdk==3.34.0"][project.optional-dependencies]