{"id":19450179,"url":"https://github.com/webexsamples/pollbot-opensource","last_synced_at":"2025-09-07T00:33:32.570Z","repository":{"id":114829199,"uuid":"609205036","full_name":"WebexSamples/Pollbot-OpenSource","owner":"WebexSamples","description":null,"archived":false,"fork":false,"pushed_at":"2024-05-07T17:51:22.000Z","size":538,"stargazers_count":3,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-25T03:37:17.125Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WebexSamples.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-03T15:42:35.000Z","updated_at":"2024-07-22T15:58:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"ef25fd55-0de7-42e4-a953-360e1b9a30f5","html_url":"https://github.com/WebexSamples/Pollbot-OpenSource","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/WebexSamples/Pollbot-OpenSource","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebexSamples%2FPollbot-OpenSource","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebexSamples%2FPollbot-OpenSource/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebexSamples%2FPollbot-OpenSource/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebexSamples%2FPollbot-OpenSource/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WebexSamples","download_url":"https://codeload.github.com/WebexSamples/Pollbot-OpenSource/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebexSamples%2FPollbot-OpenSource/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260851172,"owners_count":23072551,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-10T16:35:36.734Z","updated_at":"2025-09-07T00:33:32.553Z","avatar_url":"https://github.com/WebexSamples.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Pollbot-OpenSource\n\nThis is an open source version of [Pollbot](https://apphub.webex.com/applications/pollbot-cisco-systems-12150-78220-99857) that can be found on the Webex AppHub. Feel free to rename it and modify it to fit your needs.\n\n## 🎯 Overview\n\nPollbot-OpenSource is a comprehensive polling bot for Webex Teams that enables users to create interactive polls, surveys, and collect feedback within their Webex spaces. Built with Python and Tornado, it features both text-based commands and rich Adaptive Cards for an enhanced user experience.\n\n## ✨ Key Features\n\n- **Interactive Polling**: Create polls with multiple choice questions\n- **Adaptive Cards**: Modern, interactive UI with buttons and forms\n- **Real-time Results**: Live poll results and status updates\n- **Privacy Controls**: Public or private poll results\n- **Multiple Question Types**: Single and multiple question polls\n- **Time-based Polls**: Set poll duration and automatic expiration\n- **Comprehensive Commands**: Both typed commands and card-based interactions\n- **MongoDB Integration**: Persistent poll storage and analytics\n- **Webhook Security**: Secure webhook validation with secrets\n\n## 🚀 Getting Started\n\n### Prerequisites\n\n- Python 3.8 or higher\n- MongoDB database\n- Webex Teams bot account\n- Public web server or ngrok for webhooks\n\n### Bot Setup\n\nTo create your own Webex bot to use within this app see https://developer.webex.com/docs/bots.\n\n### Environment Configuration\n\nIn order to use this app you will need to create a `.env` file with required environment variables. A [sample](example.env) has been provided showing what the variables are that will need values provided. If you wish to handle the environment variables differently you can comment out or remove the import for dotenv, located [here](pollbot/src/settings.py#L24).\n\n### Required Webhooks\n\nThree [webhooks](https://developer.webex.com/docs/webhooks) are required and it is recommended to include a webhook secret when creating them.\n\nSee https://developer.webex.com/docs/webhooks for how to create webhooks. Be sure to use your bot token to create the webhooks.\n\nThe secret defined when creating the webhooks will need to be included in the environment variables.\n\n1. **\"resource\": \"messages\", \"event\": \"created\"** - pointed to the root of where you're hosting the app.  \n   Example: `https://example.com`\n\n2. **\"resource\": \"attachmentActions\", \"event\": \"created\"** - pointed to /cards.  \n   Example: `https://example.com/cards`\n\n3. **\"resource\": \"memberships\", \"event\": \"all\"** - pointed to /memberships.  \n   Example: `https://example.com/memberships`\n\n### Support Link Configuration\n\nIn the following cards, there is a place where you can provide your own support link so your users can contact you with any issues that may occur.\n\n- [edit_card.json](pollbot/src/cards/edit_card.json#L36)\n- [help_direct_card.json](pollbot/src/cards/help_direct_card.json#L43)\n- [help_active_card.json](pollbot/src/cards/help_active_card.json#L75)\n- [help_group_card.json](pollbot/src/cards/help_group_card.json#L48)\n- [setup_card.json](pollbot/src/cards/setup_card.json#L135)\n\n## 📦 Install and Run\n\n### Manual Installation\n\n**Clone the repository:**\n```bash\ngit clone https://github.com/WebexSamples/Pollbot-OpenSource.git\n```\n\n**Install dependencies:**\n\nTo install the required modules you can use the [requirements.txt](requirements.txt) file using pip or pip3.\n\n```bash\npip3 install -r requirements.txt\n```\n\n**Configure environment variables:**\n\nMake any changes you wish to make to the code and add your environment variables. You can rename the `example.env` file to `.env` and supply your environment variables in that file.\n\n**Run the application:**\n\nRun the app using the following command in terminal:\n```bash\npython3 pollbot.py\n```\n\n### Docker Installation\n\nAn example [Dockerfile](pollbot/Dockerfile) has been provided as well. After editing the Dockerfile and providing your custom bot and DB info you can build the Docker image and run it using the following Docker commands.\n\n**Build the Docker image:**\n```bash\ndocker build -f pollbot/Dockerfile -t pollbot-opensource .\n```\nYou can replace `pollbot-opensource` with whatever name you want.\n\n**Run the Docker container:**\n```bash\ndocker run -p 10060:10060 -i -t pollbot-opensource\n```\nIf you change the port number you'll need to update it in the Dockerfile as well and rebuild the image.\n\n## 📁 Project Structure\n\n```\nPollbot-OpenSource/\n├── pollbot.py                      # Main application entry point\n├── pollbot/                        # Core application package\n│   ├── src/                        # Source code\n│   │   ├── settings.py            # Configuration settings\n│   │   ├── basehandler.py         # Base request handlers\n│   │   ├── spark.py               # Webex API integration\n│   │   ├── mongo_db_controller.py # Database operations\n│   │   ├── card_builder.py        # Adaptive Card generation\n│   │   ├── app_helper.py          # Application utilities\n│   │   ├── alive.py               # Health check endpoints\n│   │   └── cards/                 # Adaptive Card templates\n│   │       ├── create_card.json\n│   │       ├── help_active_card.json\n│   │       ├── help_direct_card.json\n│   │       ├── help_group_card.json\n│   │       ├── results_card.json\n│   │       ├── edit_card.json\n│   │       ├── answer_card.json\n│   │       └── setup_card.json\n│   └── Dockerfile                 # Docker configuration\n├── requirements.txt               # Python dependencies\n├── example.env                    # Environment variables template\n└── README.md                      # This file\n```\n\n## 🔧 Dependencies\n\nThe application requires the following Python packages:\n\n```\ninflect                    # Natural language processing for numbers\npymongo==3.10.1           # MongoDB driver\npymongo[srv]              # MongoDB SRV record support\ntornado==4.5.2            # Web framework\nrequests                  # HTTP library\nrequests-toolbelt         # HTTP utilities\npython-dotenv            # Environment variable management\n```\n\n## ⚙️ Configuration\n\n### Environment Variables\n\nThe application uses the following environment variables:\n\n**Bot Configuration:**\n- `MY_POLLBOT_TOKEN`: Your Webex bot access token\n- `MY_POLLBOT_NAMES`: Bot names (comma-separated)\n- `MY_POLLBOT_PORT`: Port number for the application\n- `MY_POLLBOT_ID`: Bot ID from Webex\n- `MY_SECRET_PHRASE`: Webhook secret for validation\n\n**Database Configuration:**\n- `POLLBOT_MONGO_DB_URI`: MongoDB connection string\n- `POLLBOT_MONGO_DB_NAME`: Database name\n- `POLLBOT_MONGO_COLLECTION_NAME`: Collection name for polls\n\n**Application Settings:**\n- `POLLBOT_DEFAULT_DURATION`: Default poll duration in minutes\n- `POLLBOT_LOOP_SLEEP_SECONDS`: Background task sleep interval\n- `METRICS_BOT_ID`: Metrics collection bot ID\n\n**Card File Paths:**\n- `POLLBOT_CREATE_CARD_FILE`: Path to create poll card\n- `POLLBOT_HELP_ACTIVE_CARD_FILE`: Path to help card for active polls\n- `POLLBOT_HELP_GROUP_CARD_FILE`: Path to group help card\n- `POLLBOT_HELP_DIRECT_CARD_FILE`: Path to direct help card\n- `POLLBOT_RESULTS_CARD_FILE`: Path to results card\n- `POLLBOT_EDIT_CARD_FILE`: Path to edit poll card\n- `POLLBOT_ANSWER_CARD_FILE`: Path to answer card\n- `POLLBOT_OPTIONS_CARD_FILE`: Path to additional options card\n- `POLLBOT_SETUP_CARD_FILE`: Path to setup card\n\n## 🎮 Usage\n\n### Text Commands\n\n**Basic Commands:**\n- `@pollbot help` - Show help information\n- `@pollbot create poll` - Create a new poll using cards\n- `@pollbot results` - View current poll results\n- `@pollbot stop` - Stop the current poll\n- `@pollbot edit` - Edit poll settings\n\n**Advanced Commands:**\n- `@pollbot create What's your favorite color?; Red; Blue; Green` - Create poll with typed command\n- `@pollbot public` - Make poll results public\n- `@pollbot private` - Make poll results private\n- `@pollbot duration 60` - Set poll duration to 60 minutes\n\n### Card-Based Interactions\n\nThe bot provides rich interactive cards for:\n- **Poll Creation**: Step-by-step poll setup\n- **Answer Selection**: Multiple choice answers\n- **Results Display**: Real-time poll results\n- **Poll Management**: Edit and control poll settings\n\n### Poll Features\n\n**Question Types:**\n- Single question polls\n- Multiple question polls\n- Anonymous voting options\n- Multi-answer selection\n\n**Privacy Options:**\n- Public results (visible to all)\n- Private results (visible to creator only)\n- Anonymous voting\n\n**Time Controls:**\n- Set custom duration\n- Automatic poll expiration\n- Real-time countdown\n\n## 🏗️ Architecture\n\n### Core Components\n\n**Main Application (pollbot.py):**\n- Tornado web server setup\n- Route configuration\n- Request handling coordination\n\n**Request Handlers:**\n- `MainHandler`: Processes incoming messages\n- `CardsHandler`: Handles Adaptive Card interactions\n- `CustomMembershipsHandler`: Manages space memberships\n- `AliveHandler`: Health check endpoints\n\n**Data Layer:**\n- `MongoController`: Database operations\n- `MetricsDB`: Analytics and usage tracking\n- `Settings`: Configuration management\n\n**Business Logic:**\n- `AppHelper`: Application utilities and background tasks\n- `CardBuilder`: Adaptive Card generation\n- `Spark`: Webex API integration\n\n### Database Schema\n\n**Active Polls Collection:**\n```json\n{\n  \"room_id\": \"string\",\n  \"creator_id\": \"string\",\n  \"creator_name\": \"string\",\n  \"questions\": [\n    {\n      \"question\": \"string\",\n      \"answers\": [\"string\"],\n      \"responses\": {}\n    }\n  ],\n  \"created_date\": \"datetime\",\n  \"duration\": \"integer\",\n  \"private\": \"boolean\",\n  \"anonymous\": \"boolean\"\n}\n```\n\n## 🔐 Security\n\n### Webhook Validation\n\nThe application validates incoming webhooks using HMAC-SHA1 signatures:\n\n```python\nsecret_equal = Spark.compare_secret(\n    self.request.body, \n    self.request.headers.get('X-Spark-Signature'), \n    Settings.secret_phrase\n)\n```\n\n### Bot Message Filtering\n\nAutomatically filters out messages from other bots:\n\n```python\nif webhook['data']['personEmail'].endswith('@sparkbot.io') or \n   webhook['data']['personEmail'].endswith('@webex.bot'):\n    print(\"Message from another bot. Ignoring.\")\n```\n\n### Environment Variable Protection\n\nSensitive configuration stored in environment variables:\n- Bot tokens\n- Database credentials\n- Webhook secrets\n- API keys\n\n## 📊 Analytics \u0026 Metrics\n\nThe application includes comprehensive analytics:\n\n**Usage Tracking:**\n- Command usage statistics\n- User interaction patterns\n- Poll creation metrics\n- Response analytics\n\n**Performance Monitoring:**\n- API response times\n- Database query performance\n- Error tracking\n- Resource utilization\n\n## 🚀 Deployment\n\n### Local Development\n\n1. **Set up environment variables**\n2. **Install dependencies**: `pip3 install -r requirements.txt`\n3. **Start MongoDB**\n4. **Run application**: `python3 pollbot.py`\n5. **Configure webhooks** pointing to your local server\n\n### Production Deployment\n\n**Docker Deployment:**\n```bash\n# Build image\ndocker build -f pollbot/Dockerfile -t pollbot-opensource .\n\n# Run container\ndocker run -p 10060:10060 -i -t pollbot-opensource\n```\n\n**Environment Configuration:**\n- Use environment variables for configuration\n- Secure MongoDB connection\n- HTTPS for webhook endpoints\n- Load balancing for high availability\n\n### Health Checks\n\nThe application provides health check endpoints:\n- `/alive` - Basic health check\n- `/ready` - Readiness check with database connectivity\n\n## 🧪 Testing\n\n### Manual Testing\n\n1. **Add bot to Webex space**\n2. **Test basic commands**: `@pollbot help`\n3. **Create poll**: `@pollbot create poll`\n4. **Test card interactions**\n5. **Verify webhook delivery**\n\n### Debug Mode\n\nEnable debug mode for additional features:\n```bash\npython3 pollbot.py --debug\n```\n\nDebug mode provides:\n- Additional test cards\n- Detailed logging\n- Development utilities\n\n## 🔧 Customization\n\n### Adding New Commands\n\n1. **Add command logic** in `MainHandler.post()`\n2. **Update help text** in `BaseHandler.help_msg()`\n3. **Create card templates** if needed\n4. **Test command functionality**\n\n### Custom Card Templates\n\n1. **Create JSON card file** in `pollbot/src/cards/`\n2. **Add file path** to environment variables\n3. **Update `CardBuilder`** to use new cards\n4. **Test card rendering**\n\n### Database Customization\n\n1. **Modify schema** in `MongoController`\n2. **Update queries** as needed\n3. **Add indexes** for performance\n4. **Test data operations**\n\n## 🐛 Troubleshooting\n\n### Common Issues\n\n**Webhook Not Receiving Messages:**\n- Verify webhook URLs are correct\n- Check webhook secret configuration\n- Ensure bot is added to space\n- Verify firewall/network access\n\n**Database Connection Issues:**\n- Check MongoDB connection string\n- Verify database credentials\n- Test network connectivity\n- Review database logs\n\n**Card Rendering Problems:**\n- Validate JSON card syntax\n- Check file paths in environment variables\n- Verify card schema compliance\n- Test with simple cards first\n\n### Debug Information\n\nThe application provides extensive logging:\n- Webhook payloads\n- API responses\n- Database operations\n- Error stack traces\n\n## 📈 Performance Optimization\n\n### Database Optimization\n\n- **Indexes**: Create indexes on frequently queried fields\n- **Connection Pooling**: Use MongoDB connection pooling\n- **Query Optimization**: Optimize database queries\n- **Data Cleanup**: Regular cleanup of expired polls\n\n### Application Optimization\n\n- **Async Operations**: Use Tornado's async features\n- **Caching**: Cache frequently accessed data\n- **Resource Management**: Proper cleanup of resources\n- **Monitoring**: Track performance metrics\n\n## 🤝 Contributing\n\n1. **Fork the repository**\n2. **Create feature branch**: `git checkout -b feature/new-feature`\n3. **Make changes** and test thoroughly\n4. **Follow code style** and add documentation\n5. **Submit pull request** with detailed description\n\n### Development Guidelines\n\n- **Code Style**: Follow PEP 8 Python style guidelines\n- **Documentation**: Add docstrings and comments\n- **Testing**: Test all new features thoroughly\n- **Security**: Follow security best practices\n\n## 📄 License\n\n```\nCopyright 2022 Cisco Systems Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n```\n\n## 🔗 Related Resources\n\n- [Pollbot on Webex AppHub](https://apphub.webex.com/applications/pollbot-cisco-systems-12150-78220-99857)\n- [Webex Bot Development Guide](https://developer.webex.com/docs/bots)\n- [Webex Webhooks Documentation](https://developer.webex.com/docs/webhooks)\n- [Adaptive Cards Documentation](https://developer.webex.com/docs/api/guides/cards)\n- [Tornado Web Framework](https://www.tornadoweb.org/)\n\n## 🆘 Support\n\n- Create an issue in this repository\n- Review [Webex Developer Documentation](https://developer.webex.com/docs)\n- Contact [Webex Developer Support](https://developer.webex.com/support)\n\n---\n\n**Repository**: https://github.com/WebexSamples/Pollbot-OpenSource\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebexsamples%2Fpollbot-opensource","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebexsamples%2Fpollbot-opensource","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebexsamples%2Fpollbot-opensource/lists"}